3

I'm using jQuery hover function to hover over the box-empty class. On the hover, it replaces the box-empty to box-full.

  1. On hover over a block, how can I hover over all previous blocks too?
  2. When clicking on the block, how can I add the class box-full to all previous blocks?

Edit: Sorry, I forgot to mention that I need to include the block which has been clicked/hover also (not only the previous ones).

enter image description here

Here's my code:

HTML:

<div class="wrap"> 
    <span class="box box-empty"></span>
    <span class="box box-empty"></span>
    <span class="box box-empty"></span>
    <span class="box box-empty"></span>
</div>

jQuery:

$('.box-empty').hover(function () {
        $(this).addClass('box-full');
        $(this).removeClass('box-empty'); 
    }, function () {
        $(this).addClass('box-empty');
        $(this).removeClass('box-full');
    });

Demo: http://jsfiddle.net/aCP9x/

4

3 回答 3

4

你需要使用prevAll(). 您还需要addBack()包含当前悬停的元素。尝试这个:

$('.box-empty').hover(function () {
    $(this).prevAll().addBack().toggleClass('box-full box-empty');
});

更新的小提琴

请注意,我还使用 简化了您的代码,这意味着相同的toggleClass功能可以在.mouseentermouseleavehover

于 2013-11-02T21:30:02.907 回答
3

纯 CSS 方法:

span:hover ~ span, span:hover {
    border: 1px solid #000;
    background: #000;
}

jsFiddle在这里

正如下面的 Fabrício Matté 所提到的,您可以利用 CSS 复选框 hack,允许您有效地在选中/未选中之间切换。

于 2013-11-02T21:31:27.210 回答
0
$('.box').hover(
    function () {
        $('.box:lt(' + ($(this).index() + 1) + ')').toggleClass('box-full box-empty'); 
    }, 
    function () {
        $('.box:lt(' + ($(this).index() + 1) + ')').toggleClass('box-empty box-full');
}
);
于 2013-11-02T21:35:51.407 回答