当元素内有两个子元素时,如何仅触发一个鼠标悬停事件



最近我有一个这样的元素:

<p>Some text
<a href='#'>
<img src="">
Some text 1
</a></p>

当我在a上添加鼠标悬停事件并将鼠标悬停在Some text 1周围时,它将触发一次鼠标悬停事件。但是,当我将鼠标从Some text 1移动到图像时,将触发另一个鼠标悬停事件。如何确保鼠标悬停事件仅触发一次?谢谢!

这里发生的事情就是所谓的"事件泡沫"。您只需在 a 标记上应用鼠标悬停事件。如果在 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>

我已经解决了我的问题。我发现使用鼠标输入不会有这种问题。

最新更新