【问题标题】:How to trigger mouseover event only one when there are two child element inside the element当元素内有两个子元素时如何仅触发一个鼠标悬停事件
【发布时间】:2018-09-11 02:41:40
【问题描述】:

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

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

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

【问题讨论】:

  • 你能展示你的jquery代码吗?

标签: jquery mouseover


【解决方案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>

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2013-02-22
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-27
      • 2021-11-10
      • 2012-10-30
      相关资源
      最近更新 更多