Alv*_*aro 6 javascript mouseenter event-delegation dom-events
如何为mouseenter事件实现事件委托?
我正在寻找与此 jQuery 代码等效的代码,但无法理解 jQuery 如何在内部执行此操作:
$(document).on('mouseenter', '.demo', foo);
Run Code Online (Sandbox Code Playgroud)
我已经看到了关于它的另一个问题,但没有提供适当的解决方案。
我还阅读了有关 mouseenter和委托的Mozilla 文档,除了说它与任何浏览器都不兼容之外,他们提供的示例在 JS 控制台上抛出错误并且不起作用。
我还检查了这个 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
});
Run Code Online (Sandbox Code Playgroud)
你可以在这个 jsfiddle 中使用它。
Luc*_*one 13
您必须在捕获阶段添加事件侦听器,true作为第三个参数传递:
document.body.addEventListener("mouseenter", function(e) {
if(e.target.className === "demo") {
console.log("catched");
}
},true); // capturing phase
Run Code Online (Sandbox Code Playgroud)
你可以做一些更详细的事情来捕捉选择器。但这是关键。
演示在这里https://codepen.io/anon/pen/Xqaxwd
| 归档时间: |
|
| 查看次数: |
1680 次 |
| 最近记录: |