当元素中有两个子元素时,如何只触发一个mouseover事件

问题描述 投票:0回答:2

最近我有这样一个元素:

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

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

jquery mouseover
2个回答
0
投票

这里发生的是所谓的'事件泡泡'。您只需要在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>

0
投票

我已经解决了我的问题。我发现使用mouseenter代替不会出现这种问题。

© www.soinside.com 2019 - 2024. All rights reserved.