gpt4 book ai didi

javascript - 防止 :hover bubbling

转载 作者:搜寻专家 更新时间:2023-10-31 22:53:03 26 4
gpt4 key购买 nike

如果我们将鼠标悬停在子元素上,如何防止父元素悬停?

这是代码

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 行为保持不变。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com