javascript - 使用普通 JavaScript 的 mouseenter 委托(delegate)?

标签 javascript mouseenter dom-events event-delegation

如何为 mouseenter 事件实现事件委托(delegate)?

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

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

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

我也读过 Mozilla docs regarding mouseenter和委托(delegate),除了说它与任何浏览器不兼容之外,他们提供的示例在 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 .

最佳答案

您必须在 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

关于javascript - 使用普通 JavaScript 的 mouseenter 委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50177348/

相关文章:

javascript - 来自 matplotlib 的交互式_独立_输出

java - 当 MouseEnter 事件触发时显示弹出窗口

javascript - 当按键 "pressed"时,捕获 HTML 按钮上的 mousedown 事件

javascript - window.onload 与 $(document).ready()

javascript - 使用 ajax 加载选项卡内容 onclick

javascript - 在 CSS 转换中启用 vendor 前缀会使回调触发两次

jQuery:我的菜单栏中的奇怪行为

javascript - 此 JavaScript 代码是否会通过禁用一个按键来影响其他按键事件?

javascript - 拖动面板不会降低不透明度

javascript - jQuery 鼠标离开输入隐藏显示