因为简单来说path
不存在于MouseEvent
or WheelEvent
类型,我正在使用替代方案:composedPath
方法。直到现在我还无法体验到它们之间的区别。我包裹了我的wheel
听众与requestAnimationFrame
,令人惊讶的是composedPath
返回一个空数组。举个例子:
window.addEventListener('click', e => {
console.log('at event:', Array.from(e.composedPath()));
setTimeout(() => {
console.log('after event:', Array.from(e.composedPath()));
}, 0)
})
#test {
width: 120vw;
height: 120vh;
}
<div id='test'></div>
(建议检查浏览器的控制台,因为window
有点大,无法滚动浏览)
如果有人知道我如何解决这个问题,那么知道它会很高兴,但问题主要是要了解造成差异的原因。
该规范定义了此行为。在步骤结束时调度事件 https://dom.spec.whatwg.org/#dispatching-events, 我们有:
- (循环遍历祖先元素,将它们添加到事件的路径中)
...
- Set event’s path https://dom.spec.whatwg.org/#event-path到空列表。
也就是说,在第5步中浏览器填写路径信息,在第8步中(所有事件处理完成后),规范明确规定浏览器必须清除路径信息。
该规范的特点是没有说why, but Kaiido https://stackoverflow.com/users/3702797/kaiido 指出 https://stackoverflow.com/questions/62181537/why-does-composedpath-on-event-returns-different-value-when-delayed/74610934?noredirect=1#comment131699356_74610934 that 添加步骤 8 的提交 https://*%20The%20path%20you%20get%20back%20is%20determined%20in%20part%20by%20the%20%60currentTarget%60%20of%20the%20event%20you%20call%20%60composedPath%60%20on%20(in%20particular%20in%20relation%20to%20the%20shadow%20DOM),%20which%20of%20course%20varies%20depending%20on%20what%20event%20listener%20is%20active.%20Once%20the%20event%20has%20been%20fully%20dispatched,%20%60currentTarget%60%20is%20set%20to%20%60null%60.%20If%20you%20work%20through%20the%20steps%20of%20%5B%60composedPath%60%5D%5B2%5D,%20you%27ll%20see%20that%20even%20if%20the%20path%20information%20hadn%27t%20been%20cleared%20when%20dispatch%20was%20complete,%20calling%20%60composedPath%60%20when%20%60currentTarget%60%20is%20%60null%60%20would%20just%20return%20the%20path%20%60%5Bnull%5D%60%20(if%20I%27m%20reading%20the%20steps%20correctly),%20which%20wouldn%27t%20be%20of%20any%20use.主要关注与 Shadow DOM 相关的事件路径的处理。无论如何,你返回的路径部分取决于currentTarget
您调用的事件的composedPath
on(特别是与影子 DOM 相关),以及currentTarget
仅当事件正在被主动调度时才有意义(一旦事件被完全调度,currentTarget
被设定为null
)。即使步骤 8 没有清除路径,如果我正在阅读以下步骤composedPath https://dom.spec.whatwg.org/#dom-event-composedpath正确,它只会返回路径[null]
当被呼叫时currentTarget
is null
,这没有任何用处。 (对于非 Shadow-DOM 的原因,这也是有意义的:事件对象通常被永远不会调用的函数关闭composedPath
,因此不必要地将这些信息保留在内存中是有意义的。路径中的任何元素稍后从 DOM 中删除都会无缘无故地弄乱内存。但证据表明这并不是添加步骤 8 的主要动机。)
如果您需要事件的路径,只需在处理期间而不是之后获取它即可。
window.addEventListener("click", (e) => {
const path = Array.from(e.composedPath(), (e) => e === window ? "window" : e.nodeName);
setTimeout(() => {
console.log(path);
}, 0);
});
window.addEventListener("click", (e) => {
const path = Array.from(e.composedPath(), (e) => e === window ? "window" : e.nodeName);
setTimeout(() => {
console.log(path);
}, 0);
});
#test {
width: 120vw;
height: 120vh;
}
<div id='test'></div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)