问题描述
我有一个绝对定位的div,我试图跟踪鼠标何时移动它以及鼠标何时离开。不幸的是,单击框中的文本偶尔会触发mouseleave事件。
I have an absolutely-positioned div, and I'm trying to keep track of when the mouse moves over it, and when the mouse leaves. Unfortunately clicking on the text in the box occasionally triggers the mouseleave event.
演示:
如何防止这种情况?
JS
let tooltip = document.createElement('div');
tooltip.innerHTML = 'HELLO WORLD';
tooltip.setAttribute('class', 'tooltip');
tooltip.style.display = 'none';
tooltip.onclick = evt => {
console.log('click')
evt.stopPropagation();
}
tooltip.ondblclick = evt => {
console.log('double click')
evt.stopPropagation();
}
tooltip.onmouseenter = () => {
console.log('tooltip mouse OVER');
}
tooltip.onmouseleave = () => {
console.log('tooltip mouse OUT')
}
tooltip.style.left = '290px';
tooltip.style.top = '50px';
tooltip.style.display = 'block';
document.body.appendChild(tooltip);
HTML
<div style="width: 300px; height: 300px; background-color: lightblue">
</div>
CSS
.tooltip {
position: absolute;
/*display: none;*/
left: 100;
top: 100;
min-width: 80px;
height: auto;
background: none repeat scroll 0 0 #ffffff;
border: 1px solid #6F257F;
padding: 14px;
text-align: center;
}
推荐答案
这似乎是个bug (我可以在Chrome中重现它,点击鼠标按下并且鼠标紧跟在彼此之后快速发生)。
This seems to be a bug (I could reproduce it in Chrome with clicks that have the mouse down and mouse up happening rapidly after each other).
我建议通过在事件被触发时检查鼠标是否仍在元素上来解决此问题:
I would suggest to work around this issue by checking whether the mouse is still over the element at the moment the event is fired:
tooltip.onmouseleave = (e) => {
if (tooltip === document.elementFromPoint(e.clientX, e.clientY)) {
console.log('false positive');
return;
}
console.log('tooltip mouse OUT')
}
缺点是当浏览器窗口失去焦点时,这也被认为是误报。如果这对您来说是个问题,请查看。
The downside is that when the browser window loses focus, that is also considered a false positive. If that is an issue for you, then check this answer.
这篇关于点击触发Mouseleave的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!