2012-09-17 203 views

回答

3

使用:hover選擇的組合和~一般兄弟選擇:

div.margin:hover ~.margin2 
{ 
    background: #00f; 
} 

將鼠標懸停在2區,你會看到其他分區的變化。

爲此,div必須是兄弟姐妹(具有相同的父元素)。

http://jsfiddle.net/Kyle_Sevenoaks/mmcRp/

5

在你的情況下,與元素,您希望後更改爲你懸停元素,這意味着你有這樣的結構:

<div id="one"></div> 
<!--you could have some elements between them--> 
<div id="two"></div> 

或類似:

<div id="one"> 
    <!--maybe some elements--> 
     <div id="two"></div> 
    <!----> 
</div> 

在第一種情況下(#one#two個兄弟姐妹,那就是他們都在同一水平=具有相同的父),使用the general sibling combinator~),像這樣:

#one:hover ~ #two { /* style changes */ } 

DEMO何時#one#two是兄弟姐妹和#one是之前的情況在HTML中爲#two

在第二種情況下(#two後裔#one),您可以使用:

#one:hover #two { /* style changes */ } 

DEMO的情況下#two#one後裔。

但是,如果你想#one在HTML之前更改是一個元素,那就是目前(meaning that this could change in the future)不可能有單獨的CSS(如果你想知道爲什麼,然後this article提供的解釋)。


但在這種情況下,當#two#one之前的HTML,你可以用JavaScript做。

var one = document.getElementById('one'), 
    two = document.getElementById('two'); 
one.addEventListener('mouseover', function(){ 
    two.style.opacity = 1; 
}, true); 
one.addEventListener('mouseout', function(){ 
    two.style.opacity = 0; 
}, true); 

DEMO

如果你正在使用像jQuery庫,那麼它得到:例如,如果#two透明度最初0,那麼你可以使用它徘徊#one時更改爲1更簡單:

$('#one').hover(function(){ 
    $('#two').css({'opacity': 1})}, 
function(){ 
    $('#two').css({'opacity': 0}) 
});​​ 

DEMO

相關問題