如果我们悬停在子元素上,如何防止父元素的悬停效果?以下是代码:
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行为保持不变。