使用vanilla JavaScript的mouseenter委托?

时间:2018-05-04 14:30:03

标签: javascript mouseenter dom-events event-delegation

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

2 个答案:

答案 0 :(得分:1)

您必须在capturing fase上添加事件侦听器,并将Severity Code Description Project File Line Suppression State Error LNK1120 3 unresolved externals MayaNK2Node C:\Users 1 Error LNK2001 unresolved external symbol "public: static class NanoKontrol2 MayaNK2Node::nanoKONTROL2" (?nanoKONTROL2@MayaNK2Node@@2VNanoKontrol2@@A 1 Error LNK2001 unresolved external symbol "unsigned char tempName" (?tempName@@3EA) Error LNK2001 unresolved external symbol "unsigned char tempName" (?tempName@@3EA) Error LNK2001 unresolved external symbol "unsigned char tempValue" (?tempValue@@3EA) Error LNK2001 unresolved external symbol "unsigned char tempValue" (?tempValue@@3EA) 作为第三个参数传递:

true

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

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

答案 1 :(得分:-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>