开发者

When hovering parent div, change bg color of child divs

I have the following setup:

<div class="parent">
  <div class="child">
  </div>
  <div class="child">
  </div>
  <div class="child">
  </div>
</div>

I'm trying to change all the background color of all of them at the same time, when the mouse is hovering over any one of them. I tried:

<script type="text/javascript">
 $(function() {
    $('.parent').hover( function(){
       $(this).css('background-color', 'gray');
    },
     function(){
      $(this).css('background-color', 'red');
    });
 });
 </script>

But, the color is not "showing through" the children <div>s.

Is there a way to choose the descendents of "this". I have many of these sets in a row, so I think I need to use "this" so I don't have the call each parent by id. I'm thinking something like this:

<script type="text/javascript">
 $(function() {
    开发者_运维技巧$('.parent').hover( function(){
       $(this "div").css('background-color', 'gray');
    },
     function(){
      $(this "div").css('background-color', 'red');
    });
 });
 </script>

But, can't quite get it to work - all the examples on jquery.com use the id selector... none use "this".

Thanks a lot!


If you're not targeting IE6, no need to use JavaScript, pure CSS will do the trick:

.parent, .child {
    background-color:red;
}

.parent:hover, .parent:hover .child {
    background-color:gray;
}


have you already tried .children()?

jQuery API


you can use .find()

$(this).find('div').css('background-color','red');

http://api.jquery.com/children/


try this:

 $(function() {
    $('.parent').hover( function(){
       $(this).children("div").css('background-color', 'gray');
    },
     function(){
       $(this).children("div").css('background-color', 'red');
    });
 });

demo: http://jsfiddle.net/zt9M6/


You're using $() with mixed arguments - it's either got to be a string as a selector (div), or just a DOM element (this). To select all divs within the context of this, try calling it like this:

<script type="text/javascript">
 $(function() {
    $('.parent').hover( function(){
       $("div", this).css('background-color', 'gray');
    },
     function(){
      $("div", this).css('background-color', 'red');
    });
 });
 </script>

From http://api.jquery.com/jQuery/#jQuery1


Do it with CSS classes

.parent .child{
    background-color: red;
}

.hoverstyle .child{
    background-color: gray;
}

$(.parent')hover(function() {
    $(this).addClass("hoverstyle"):
},
function(){
    $(this).removeClass("hoverstyle");
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜