当悬停父div时,更改子div的bg颜色

And*_*sen 1 html javascript css jquery this

我有以下设置:

<div class="parent">
  <div class="child">
  </div>
  <div class="child">
  </div>
  <div class="child">
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

当鼠标悬停在其中任何一个上时,我正在尝试同时更改所有这些背景颜色.我试过了:

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

但是,颜色并没有"透过"孩子们<div>.

有没有办法选择"这个"的后代.我连续有很多这样的集合,所以我认为我需要使用"this"所以我没有通过id调用每个父节点.我在想这样的事情:

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

但是,无法让它工作 - jquery.com上的所有示例都使用id选择器......没有使用"this".

非常感谢!

dev*_*ler 5

如果你没有针对IE6,不需要使用JavaScript,那么纯CSS就可以解决这个问题:

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

.parent:hover, .parent:hover .child {
    background-color:gray;
}
Run Code Online (Sandbox Code Playgroud)