gpt4 book ai didi

javascript - window.onkeydown 和 document.onkeydown 有区别吗?

转载 作者:搜寻专家 更新时间:2023-11-01 05:04:56 26 4
gpt4 key购买 nike

我在网上看到的大部分代码都使用了document.onkeydown,但是MDN只列出了window.onkeydown . This comment还建议使用 window.onkeydown。使用其中一个有什么区别或原因吗?

最佳答案

请参阅 Event dispatch and DOM event flow 中的下图:

graphical representation of an event dispatched in a DOM tree using the DOM event flow

一共有三个event phases :

  • The capture phase: the event object must propagate through the target's ancestors from the defaultView to the target's parent. This phase is also known as the capturing phase. Event listeners registered for this phase must handle the event before it reaches its target.

  • The target phase: the event object must arrive at the event object's event target. This phase is also known as the at-target phase. Event listeners registered for this phase must handle the event once it has reached its target. If the event type indicates that the event must not bubble, the event object must halt after completion of this phase.

  • The bubble phase: the event object propagates through the target's ancestors in reverse order, starting with the target's parent and ending with the defaultView. This phase is also known as the bubbling phase. Event listeners registered for this phase must handle the event after it has reached its target.

因此,主要区别在于,在冒泡阶段,添加到window 的事件监听器将在添加到document 的事件监听器之后处理事件;在捕获阶段之前。

关于javascript - window.onkeydown 和 document.onkeydown 有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27073074/

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