2011-02-27 143 views
1

我有以下设置:当父徘徊格,改变孩子的背景颜色的div

<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> S上的颜色是不是 “通过展示”。

有没有办法选择“this”的后代。我有很多这样的组合,因此我认为我需要使用“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选择......没有用“本”。

非常感谢!

+0

也许t他就是你要找的东西:http://api.jquery.com/children/。 – pimvdb 2011-02-27 19:59:00

回答

2

试试这个:

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

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

0

您正在使用带有混合参数的$() - 它可能是一个字符串作为选择器(div),或者只是一个DOM元素(this)。向this范围内选择所有div S,尝试调用它像这样:

<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

0

与CSS类

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

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

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

做,如果你不针对IE6,不需要使用JavaScript,纯CSS就可以做到这一点:

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

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