2011-02-27 103 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; 
}