使css:悬停只影响父元素
问题描述:
在css中,当一个子事件悬停时,如何停止在父元素中触发的:hover
事件,以便它只在父级本身被占用时触发?在这种情况下,我的子元素实际上被定位在它的父元素之外,并且具有绝对定位,所以当父子变得徘徊时父变化有点奇怪。使css:悬停只影响父元素
我做了一个JSFiddle来说明这个问题。
这是我使用过的解决方案的JSFiddle。
答
有一个纯CSS的解决方案(甚至是两个实际上),但两者是有代价的。
您可以添加指针事件:无;到你的子元素 - 但它不会回应它自己的悬停样式。不幸的是,在IE 11以下版本(http://caniuse.com/#search=pointer-events)中不支持Pointer-events。
将父元素(除了定位的子元素)的内容包装到另一个元素中(这是此方法的成本)并将悬停样式应用于此包装器。
这两种方法的例子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; }
答
简单地说:不要嵌套你的#inner
div
里面。小演示: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。
我不认为这是必要的。 – BoltClock
@BoltClock嗯,我已经尝试过没有它;显然'html'和'body'在默认情况下不会获得'position:relative;'。 – Chris
该元素需要嵌套在它的父亲 – CupOfTea696