使 css :hover 只影响父元素

2023-11-29前端开发问题
180

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

问题描述

在css中,当子事件悬停时,如何停止在父元素中触发 :hover 事件,以便仅在父元素本身悬停时触发?在这种情况下,我的子元素实际上以绝对定位定位在其父元素之外,因此当子元素悬停时父元素发生变化时,这有点奇怪.

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.

我做了一个JSFiddle来说明问题.

I made a JSFiddle to illustrate the problem.

这是我的示例所用解决方案的 JSFiddle.

推荐答案

有一个纯 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; }

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

The End

相关推荐

layui 单选框、复选框、下拉菜单不显示问题如何解决?
1. 如果是ajax嵌套了 页面, 请确保 只有最外层的页面引入了layui.css 和 layui.js ,内层页面 切记不要再次引入 2. 具体代码如下 layui.use(['form', 'upload'], function(){ var form = layui.form; form.render(); // 加入这一句});...
2024-11-09 前端开发问题
313

layui要如何改变时间日历布局大小?
问题描述 我想改变layui时间日历布局大小,这个要怎么操作呢? 解决办法 可以用css样式对时间日历进行重新布局,具体代码如下: !DOCTYPE htmlhtmlheadmeta charset="UTF-8"title/titlelink rel="stylesheet" href="../../layui/css/layui.css" /style#test-...
2024-10-24 前端开发问题
271

CoffeeScript 总是以匿名函数返回
CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)...
2024-04-20 前端开发问题
13

getFullYear 在一年的第一天返回前一年
getFullYear returns year before on first day of year(getFullYear 在一年的第一天返回前一年)...
2024-04-20 前端开发问题
6

如何制作 TextGeometry 多线?如何将它放在一个正方形内,以便它像 html 文本一样包裹在 div 内?
How do I make a TextGeometry multiline? How do I put it inside a square so it wraps like html text does inside a div?(如何制作 TextGeometry 多线?如何将它放在一个正方形内,以便它像 html 文本一样包裹在 div 内?) - IT屋-程序员软件开发技术分享社...
2024-04-20 前端开发问题
6

如何在开发网站时使用coffeescript?
How to use coffeescript in developing web-sites?(如何在开发网站时使用coffeescript?)...
2024-04-20 前端开发问题
10