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

时间:2011-02-27 19:55:39

标签: javascript jquery html css this

我有以下设置:

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

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

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

但是,颜色并没有“透过”孩子<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>

但是,不能让它工作 - jquery.com上的所有示例都使用id选择器......没有使用“this”。

非常感谢!

6 个答案:

答案 0 :(得分:5)

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

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

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

答案 1 :(得分:2)

你已经尝试过了.children()?

jQuery API

答案 2 :(得分:2)

您可以使用.find()

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

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

答案 3 :(得分:2)

试试这个:

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

演示: http://jsfiddle.net/zt9M6/

答案 4 :(得分:0)

你正在使用带有混合参数的$() - 它必须是一个字符串作为选择器(div),或者只是一个DOM元素(this)。要在div的上下文中选择所有this,请尝试按以下方式调用:

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

来自http://api.jquery.com/jQuery/#jQuery1

答案 5 :(得分:0)

使用CSS类

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

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

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