使css:hover只影响父元素 [英] Make css :hover only affect parent element

查看:1944
本文介绍了使css:hover只影响父元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在css中,当子事件被悬浮时,如何阻止父元素中触发的:hover 事件,因此只有在父元素本身徘徊?在这种情况下,我的子元素实际上位于它的父元素之外的绝对定位,所以当父变化时,当孩子被徘徊时有点奇怪。



JSFiddle 来说明问题。



这是一个 JSFiddle 对我的示例使用的解决方案。

解决方案

有一个纯CSS解决方案(事实上甚至两个),但都是有代价的。


  1. 您可以添加指针事件:none;到你的子元素 - 但它不会响应它自己的悬停样式。 指针事件不幸在IE 11以下版本中不受支持( http://caniuse.com/#search=pointer-events )。


  2. 将父元素(除了已定位子元素)的内容包含在另一个元素中(即此方法的成本),并将悬停样式应用于此包装器。


两种方法的示例这里

  .parent-2,
.parent {position:relative;背景:#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; }
/ *在歌剧中不起作用,即* /


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


In css, how can I stop the :hover event being triggered in a parent element when a child event is hovered, so that it only gets triggered when the parent itself gets hovered? In this case my child element is actually positioned outside it's parent element with absolute positioning, so it's a bit weird when the parent changes when the child gets hovered.

I made a JSFiddle to illustrate the problem.

Here's a JSFiddle of the used solution to my example.

解决方案

There is a pure css solution (even two in fact) but both come at a cost.

  1. You can add pointer-events:none; to your child element - but it will not respond to it's own hover styles either. Pointer-events unfortunately are not supported in IE below version 11 (http://caniuse.com/#search=pointer-events).

  2. Wrap content of your parent element (apart from positioned child) in another one (thats the cost of this method) and apply hover styles to this wrapper.

Examples of both methods 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; }

这篇关于使css:hover只影响父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆