addEventListener 应该添加到 window 还是 document?


二者之间有什么不同呢?

event JavaScript

neet族 9 years, 7 months ago

应该是document下的对象上吧。
document本身属于window中的一个对象。
但是他又属于dom对象,和文档元素有联系。

永远的HIME answered 9 years, 7 months ago

window、document都可以添加,看一下w3c关于dom事件模型的定义:

  • 捕获
    The event object must propagate through the target's ancestors from the Window 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 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 event object propagates through the target's ancestors in reverse order, starting with the target's parent and ending with the Window. 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。

因此,你使用 window.addEventListener document.addEventListener 来处理页面上的事件,区别仅仅在于,不同事件模型上,处理的顺序不一样:

  • 捕获,window先于document
  • 冒泡,document先于window

我们可以 addEventListener 的第三个参数来使用不同的事件模型, true 代表我们想在捕获阶段处理事件, false 代表我们想在冒泡阶段处理事件,默认是 false

ytzzty answered 9 years, 7 months ago

Your Answer