最近我有这样一个元素:
<p>Some text
<a href='#'>
<img src="">
Some text 1
</a></p>
当我在a
上添加一个mouseover事件并且我在Some text 1
周围盘旋时,它将触发一次mouseover事件。但是,当我将鼠标从Some text 1
移动到图像时,会触发另一个鼠标悬停事件。如何确保只触发一次鼠标悬停事件?非常感谢你!
这里发生的是所谓的'事件泡泡'。您只需要在a标记上应用mouseover事件。如果在p标签上应用if,则当鼠标悬停在任何子标签和p标签本身时会触发。所有子元素都将事件发送到堆栈。
<!--
This will cause the duplicated fired events when mouse over any element
inside the p tag and over the child elements
-->
<p id="hoverOverMe">Some text
<a href='#'>
<img src="">
Some text 1
</a>
</p>
工作实例
<p >Some text
<a id="hoverOverMe" href='#'>
<img src="">
Some text 1
</a>
</p>
<script>
document.querySelector('#hoverOverMe')
.addEventListener('mouseover', event => {
console.log(event);
});
</script>
我已经解决了我的问题。我发现使用mouseenter代替不会出现这种问题。