![](/img/trans.png)
[英]CSS or JS Rule for all Divs to Change BG Color of Div inside Div, Without Changing Parent Div
[英]When hovering parent div, change bg color of child divs
我有以下設置:
<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”。
非常感謝!
如果您的目標不是IE6,則無需使用JavaScript,純CSS可以解決問題:
.parent, .child {
background-color:red;
}
.parent:hover, .parent:hover .child {
background-color:gray;
}
您是否已經嘗試過.children()?
嘗試這個:
$(function() {
$('.parent').hover( function(){
$(this).children("div").css('background-color', 'gray');
},
function(){
$(this).children("div").css('background-color', 'red');
});
});
演示: http : //jsfiddle.net/zt9M6/
您正在使用帶有混合參數的$()
-它必須是一個字符串作為選擇器( div
),或者僅僅是一個DOM元素( this
)。 要選擇所有div
S的范圍內this
,嘗試調用它像這樣:
<script type="text/javascript">
$(function() {
$('.parent').hover( function(){
$("div", this).css('background-color', 'gray');
},
function(){
$("div", this).css('background-color', 'red');
});
});
</script>
用CSS類來做
.parent .child{
background-color: red;
}
.hoverstyle .child{
background-color: gray;
}
$(.parent')hover(function() {
$(this).addClass("hoverstyle"):
},
function(){
$(this).removeClass("hoverstyle");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.