gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:22:29 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com