代码之家  ›  专栏  ›  技术社区  ›  Alvaro

mouseenter委派使用vanilla JavaScript?

  •  8
  • Alvaro  · 技术社区  · 7 年前

    如何为 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 回复  |  直到 7 年前
        1
  •  16
  •   charlietfl    5 年前

    您必须在上添加事件侦听器 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

        2
  •  -2
  •   Amr Noman    7 年前

    也许你可以用 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>