Igo*_*ega 3 html javascript css sass
如果我们将鼠标悬停在其子项上,如何阻止父元素悬停?
这是代码
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') */
}
Run Code Online (Sandbox Code Playgroud)
#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;
}
Run Code Online (Sandbox Code Playgroud)
<div id="parent">
<div id="child-left"></div>
<div id="child-right"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/3tjcsyov/48/
您可以看到,如果您将鼠标悬停在红色区域上,如果考虑CSS行为,绿色区域也会悬停.是的,我们可以使用,stopPropagation
但它只会阻止js处理程序执行父元素,而CSS行为保持不变.
如果你将孩子设置pointer-events
为none
,你可以毫无任意地实现这一目标JavaScript
.
#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;
}
#child-left,
#child-right {
pointer-events: none;
}
Run Code Online (Sandbox Code Playgroud)
<div id="parent">
<div id="child-left"></div>
<div id="child-right"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/bepLktoj/
归档时间: |
|
查看次数: |
619 次 |
最近记录: |