使用vanilla JavaScript的mouseenter委托?

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

如何为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

javascript mouseenter dom-events event-delegation
2个回答
1
投票

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

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

你可以做一些更精细的事情来抓住选择器。但那是关键。

在这里演示https://codepen.io/anon/pen/Xqaxwd


-1
投票

也许你可以使用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>
© www.soinside.com 2019 - 2024. All rights reserved.