【问题标题】:How to know if an event is still bubbling?如何知道事件是否仍在冒泡?
【发布时间】:2017-12-07 10:01:16
【问题描述】:

我有一个带有一些嵌套元素的 SVG 元素。我已将 mouseout 处理程序附加到 SVG 元素。当我在 SVG 元素的中间按下鼠标并将其移出 SVG 元素时,我得到以下事件列表:

down
out <path ...>
out <circle r="39.5">
out <circle r="40">
out <circle r="49.5">
out <svg ...>
up

这意味着鼠标首先离开了路径,然后离开了三个同心圆,最后离开了 SVG 元素。我只对最后一个事件感兴趣,它影响附加了处理程序的元素。 SVG 元素获取所有其他事件,因为它们冒泡到 SVG 元素。

我怎么知道某个事件是否已冒泡?如何忽略那些不影响附加了处理程序的元素的事件?

【问题讨论】:

标签: javascript html event-bubbling


【解决方案1】:

您可以使用event.target 属性查看实际触发事件的元素。

$('#myDiv').on('click', function(e) {
  console.log(e.target.id);
});
#myDiv {
  background-color: red;
  width: 100px;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='myDiv'>
  <button id='myButton'>Click me</button>
</div>

【讨论】:

  • 如何比较元素?
  • 例如,您可以给他们 id 并进行比较
【解决方案2】:

似乎有必要检查target 是否与currentTarget 相同。 answer 到另一个 question 声称,这可以通过 === 完成。因此,我现在在 mouseout 处理程序中使用以下条件来跳过事件仍在冒泡的情况:

svg.onmouseout = function (event) {
  if (event.target === event.currentTarget) {
    // Do what needs to be done after the mouse leaves the SVG element.
  }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    相关资源
    最近更新 更多