【发布时间】:2019-07-03 09:28:13
【问题描述】:
如果我们将鼠标悬停在其子元素上,如何防止父元素悬停?
这里是代码
const parent = document.getElementById('parent')
parent.onmouseover = function testAlert(e) {
/* alert('parent') */
}
const childRight = document.getElementById('child-right')
childRight.onmouseover = function f(e) {
e.stopPropagation()
/* alert('child-right') */
}
const childLeft = document.getElementById('child-left')
childLeft.onmouseenter = function f(e) {
e.stopPropagation()
/* alert('child-right') */
}
#parent {
background: green;
width: 100px;
height: 100px;
position: relative;
margin: 0 auto;
}
#parent:hover {
background: rgba(0, 0, 0, 0.8);
}
#child-left {
background: red;
width: 50px;
height: 50px;
position: absolute;
top: 0;
left: -50px;
}
#child-right {
background: red;
width: 50px;
height: 50px;
position: absolute;
top: 50px;
left: 100px;
}
<div id="parent">
<div id="child-left"></div>
<div id="child-right"></div>
</div>
https://jsfiddle.net/3tjcsyov/48/
您可以看到,如果您将鼠标悬停在红色矩形上,如果考虑 CSS 行为,绿色矩形也会悬停。是的,我们可以使用stopPropagation,但它只会阻止父元素的 js 处理程序执行,而 CSS 行为保持不变。
【问题讨论】:
-
你能用 JavaScript 代替 SCSS 添加行为吗?
-
要将鼠标悬停在子级上,您必须将鼠标悬停在父级上。我不知道可以防止这种状态。
-
请不要使用外部代码站点,除非 SO 的 sn-p 功能不够。
-
请在问题本身中发布您的代码。
-
@TemaniAfif 问题并不太宽泛。这个答案stackoverflow.com/a/54604384 符合 OP 描述的要求
标签: javascript html css sass