使用香草 JavaScript 的 mouseenter 委托?

mouseenter delegation using vanilla JavaScript?

如何为 mouseenter 事件实现事件委托?

我正在寻找与此 jQuery 代码等效的代码,但未能理解 jQuery 内部是如何实现的:

$(document).on('mouseenter', '.demo', foo);

我看过this other question about it,但没有提供合适的解决方案。

我也看过 Mozilla docs regarding mouseenter 和授权,除了说它与任何浏览器都不兼容,他们提供的示例在 JS 控制台上抛出错误并且不起作用。

我还检查了 this codepen,它在 Chrome 上也不起作用(没有尝试其他浏览器)。

有什么想法吗?

这是我目前正在尝试的方法,但 target 元素似乎总是冒泡:

document.addEventListener('mouseenter', function(e) {
    console.log('==============================');
    console.log(e.currentTarget); //document
    console.log(e.target); //document 
    console.log(e.relatedTarget); //nothing
    console.log(e.handleObj); //nothing
});

你可以玩它in this jsfiddle

也许你可以使用 mousemove 并像这样跟踪当前元素(记住父元素):

let lastTarget = null;

document.addEventListener('mousemove', function(e) {
 const target = checkWithParents(e.target);
 if (target && target != lastTarget) {
   alert('mouseenter');
 }
 lastTarget = target;
})

function checkWithParents(el) {
  while (el) {
    if (el && el.classList && el.classList.contains('demo')) {
      return el;
    }
    el = el.parentNode;
  }
  return null;
}
.demo {
  background-color: tomato;
  height: 300px;
  width: 300px;
  margin: 50px;
}
<div class="demo"><div class="inner"></div></div>
<div class="demo"><div class="inner"></div></div>

您必须在 capturing phase 上添加事件侦听器,将 true 作为第三个参数传递:

document.body.addEventListener("mouseenter", function(e) {
    if(e.target.className === "demo") {
        console.log("catched");
    }
},true); // capturing phase

您可以做一些更详细的事情来捕捉选择器。但这就是关键。

此处演示https://codepen.io/anon/pen/Xqaxwd