这是一个简单的html+css+js代码
var myDiv = document.getElementById('myDiv');
myDiv.addEventListener('mouseenter', function() {
console.log('Mouse entered the div');
});
myDiv.addEventListener('mouseleave', function() {
console.log('Unfortunately this message happens when we enter the smaller div');
});
#myDiv {
width: 300px;
height: 300px;
background-color: yellow;
position: absolute;
}
#smaller {
border: 1px solid red;
width: 100px;
height: 100px;
position: absolute;
top: 100px;
left: 100px;
}
<div>
<div id="myDiv"></div>
<div id="smaller">
</div>
</div>
这里的问题是当鼠标出现在第二个元素上方时,mouseleave 会触发。有什么好的简单的解决方案可以避免这种情况吗?尝试了另一个事件。没有运气。
附注JS 解决方案是优选的。 CSS 悬停不适合我的情况。
#smaller
div
嵌套在 #myDiv
div
内以解决问题。将
#smaller
div
放在 #myDiv
内部。这会将较小的 div 视为 #myDiv
div
的一部分,并且不会触发您的 mouseleave
事件侦听器。这不应该扰乱您的结构,因为 #smaller
div
已经在使用 position: absolute;
。
var myDiv = document.getElementById('myDiv');
myDiv.addEventListener('mouseenter', function() {
console.log('Mouse entered the div');
});
myDiv.addEventListener('mouseleave', function() {
console.log('Unfortunately this message happens when we enter the smaller div');
});
#myDiv {
width: 300px;
height: 300px;
background-color: yellow;
position: absolute;
}
#smaller {
border: 1px solid red;
width: 100px;
height: 100px;
position: absolute;
top: 100px;
left: 100px;
}
<div>
<div id="myDiv"><div id="smaller"></div>
</div>
</div>