且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使 css :hover 只影响父元素

更新时间:2023-12-01 23:51:04

有一个纯 css 解决方案(实际上甚至有两个),但都是有代价的.

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

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

  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).

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

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.

两种方法的示例这里.

.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; }