2012-08-24 58 views
2

當類別.parent的元素被移走時,它會查找類別爲.child的子元素並將CSS應用於它們。使用CSS查找某個子元素

Here is jsFiddle

是否有可能與純粹的CSS實現這個效果?

HTML:

<div class="parent" style="background:red;margin:20px;padding:20px;"> 
    <div class="child" style="background:blue;margin:20px;padding:20px;"></div> 
</div> 

<div class="parent" style="background:red;margin:20px;padding:20px;"> 
    <div class="child" style="background:blue;margin:20px;padding:20px;"></div> 
</div>​ 

的jQuery:

$('.parent').hover(
    function() { 
    $(this).find('.child').css('background','yellow'); 
    }, 
    function() { 
    $(this).find('.child').css('background','blue'); 
    } 
);​ 

回答

5

取出內嵌樣式,並把下面的樣式表:

/* CSS */ 
.parent { background: red; margin: 20px; padding: 20px; } 
.child {background blue; margin: 20px; padding: 20px;} 
.parent:hover > .child { background: yellow; } 
+0

完美,謝謝! – UserIsCorrupt

+0

沒問題:)真的很有用的小動作。看到這篇文章更多有用的選擇器:http://css-tricks.com/child-and-siblings-selectors/ –

+0

這是行不通的。內聯樣式將覆蓋它。 – animuson

1
.parent .child { 
    background: blue; 
} 

.parent:hover .child { 
    background: yellow; 
} 

應該做的工作,除了在IE版本:hover只適用於A元素(jQuery解決這個問題; CSS不。)

2

是的。

.parent .child { 
    background: blue; 
} 

.parent:hover .child { 
    background: yellow; 
} 

這複製了你的jQuery的影響。如果你從字面上的意思是「兒童」(相對於後代,這是你真正找到了什麼),那麼你要執行以下操作:

.parent > .child { 
    background: blue; 
} 

.parent:hover > .child { 
    background: yellow; 
} 

由於@hobbs notes,這並不在IE 6中工作,因爲:hover is only supported on links in IE 6

2

是的,但您應該將內聯樣式移動到類中,因此您不必使用!important聲明(否則內聯樣式將始終覆蓋樣式表)。

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

<div class="parent"> 
    <div class="child"></div> 
</div>​ 
.parent { 
    background: red; 
    margin: 20px; 
    padding: 20px; 
} 
.child { 
    background: blue; 
    margin: 20px; 
    padding: 20px; 
} 
.parent:hover .child { 
    background: yellow; 
} 

See the jsFiddle.

相關問題