如何知道一个事件是否还在冒泡?

How to know if an event is still bubbling?

我有一个包含一些嵌套元素的 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 元素。

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

您可以使用 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>

似乎有必要检查一下,如果targetcurrentTarget 相同。 to another 声称,这可以用 === 完成。所以我现在在我的 mouseout 处理程序中使用以下条件来跳过事件仍在冒泡的情况:

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