2012-09-29 222 views
7

在css中,當一個子事件懸停時,如何停止在父元素中觸發的:hover事件,以便它只在父級本身被佔用時觸發?在這種情況下,我的子元素實際上被定位在它的父元素之外,並且具有絕對定位,所以當父子變得徘徊時父變化有點奇怪。使css:懸停隻影響父元素

我做了一個JSFiddle來說明這個問題。

這是我使用過的解決方案的JSFiddle

回答

10

有一個純CSS的解決方案(甚至是兩個實際上),但兩者是有代價的。

  1. 您可以添加指針事件:無;到你的子元素 - 但它不會迴應它自己的懸停樣式。不幸的是,在IE 11以下版本(http://caniuse.com/#search=pointer-events)中不支持Pointer-events

  2. 將父元素(除了定位的子元素)的內容包裝到另一個元素中(這是此方法的成本)並將懸停樣式應用於此包裝器。

這兩種方法的例子here

.parent-2, 
.parent { position:relative; background:#ddd; width:100px; height:100px; } 
.parent:hover { background:blue; } 
.child { position:absolute; top:0; left:130px; width:100px; height:50px; border:1px solid blue; pointer-events:none; } 
/* doesn't work in opera and ie */ 


.content { position:absolute; top:0; left:0; width:100%; height:100%; z-index:0;} 
.content:hover { background:blue; } 
5

簡單地說:不要嵌套你的#innerdiv裏面。小演示:little link。請注意,我添加了:

html, body { 
    position: relative; 
} 

在這種情況下,這是必需的。

編輯:如果你堅持讓它嵌套,一點JavaScript是必要的。下面是一個示例:

var inn = document.getElementById("inner"), outt = document.getElementById("holder"); 
outt.onmouseover = function() { 
    this.style.backgroundColor = "rgb(0, 162, 232)"; /*I like this color :)*/ 
} 
outt.onmouseout = function() { 
    this.style.backgroundColor = "orange"; 
} 
inn.onmouseover = function(ev) { 
    ev.stopPropagation(); 
} 

(如果使用jQuery編寫,但想法相同,這會更短)。

這是演示:little link

+0

我不認爲這是必要的。 – BoltClock

+0

@BoltClock嗯,我已經嘗試過沒有它;顯然'html'和'body'在默認情況下不會獲得'position:relative;'。 – Chris

+0

該元素需要嵌套在它的父親 – CupOfTea696