Jquery - 同时更改更多背景

时间:2012-04-29 16:36:42

标签: jquery

我正在使用四个看起来如下的DIV:

<div class"first">1</div>
<div class"second">2</div>
<div class"third">3</div>
<div class"fourth">4</div>

如果光标位于“第二个”DIV上,则该DIV的背景应该与前一个div(“first”)的背景一样。此外,如果光标悬停在“第三”DIV上,则前一个(“第一个”和“第二个”)应该改变背景颜色。如果光标位于div“4th”上,则前三个DIV(“first”,“second”和“third”)应该改变背景。

如何使用Jquery做到这一点?

2 个答案:

答案 0 :(得分:4)

我建议如下:

$('div').hover(
function(){
    $(this).prevAll().css('background-color','#f00');
},
function(){
    $(this).prevAll().css('background-color','#fff');
});

JS Fiddle demo

请注意,您的HTML在=class(等)之间需要"first"

答案 1 :(得分:0)

=== EDITED ===

jsFiddle:http://jsfiddle.net/sw9YV/10/

试试这个html:

 <div id="group1">
    <div class="first hoverMe">1</div>
    <div class="second hoverMe">2</div>
    <div class="third hoverMe">3</div>
    <div class="fourth hoverMe">4</div>
</div>
<br /><br /><br />
<div id="group2">
    <div class="first hoverMe">1</div>
    <div class="second hoverMe">2</div>
    <div class="third hoverMe">3</div>
    <div class="fourth hoverMe">4</div>
</div>​

和这个js:

 $(".hoverMe").mouseover(function(){
    $(this).css("background-color","#d3d3d3"); 
    $(this).prevAll(".hoverMe").css("background-color","#d3d3d3");
});

$(".hoverMe").mouseout(function(){
   $(this).css("background-color",""); 
   $(this).prevAll(".hoverMe").css("background-color","");
});
​