2015-07-11 63 views
1

這大概很容易實現,但我無法弄清楚如何去做。我想,當你將鼠標懸停在第一個元素上時,改變第二個和第三個元素的不透明度(使它們出現)。如何影響下一個元素和元素後

JSFiddle

.two{ 
 
    opacity:0; 
 
} 
 
.three{ 
 
    opacity:0; 
 
} 
 
.one:hover + .two, .one:hover + .three{ 
 
    opacity:1; 
 
}
<div class = "one"> 
 
    <h1>one</h1> 
 
</div> 
 
<div class = "two"><h1>two</h1></div> 
 
<div class = "three"><h1>three</h1></div>

然後,我會希望有這樣的事情:

.one:hover + .two, ++.three{ 
    opacity:1; 
} 

回答

1

你可以使用General sibling selectorJSFiddle):

.two { 
 
    opacity: 0; 
 
} 
 

 
.three { 
 
    opacity: 0; 
 
} 
 

 
.one:hover ~ .two, .one:hover ~ .three { 
 
    opacity: 1; 
 
}
<div class = "one"> 
 
    <h1>one</h1> 
 
</div> 
 
<div class = "two"> 
 
    <h1>two</h1> 
 
</div> 
 
<div class = "three"> 
 
    <h1>three</h1> 
 
</div>

-1
.one:hover + .two, .one:hover + .three{ 
    opacity:1; 
} 
+0

謝謝你的努力,但這似乎並不奏效。 –

1

+組合子同時連接兩個連續的兄弟姐妹。爲了達到兩步之遙的兄弟姐妹,您將相應地需要使用+兩次,一次爲您跨越的每個兄弟姐妹。

結果選擇器是.one:hover + .two + .three

.two, .three { 
 
    opacity: 0; 
 
} 
 
.one:hover + .two, 
 
.one:hover + .two + .three { 
 
    opacity: 1; 
 
}
<div class="one"><h1>one</h1></div> 
 
<div class="two"><h1>two</h1></div> 
 
<div class="three"><h1>three</h1></div>

您還可以使用~組合子,但是這需要.one.two.three是父元素的唯一孩子(或者至少後兩個是唯一的實例其種類爲.one),在這種情況下,您最好將其縮短爲.one:hover ~ div,而不是單獨針對每個兄弟姐妹。使用+組合器更保守並且不易出錯。

相關問題