javascript - addEventListener 应该添加到 window 还是 document?
黄舟
黄舟 2017-04-10 15:01:22
[JavaScript讨论组]

二者之间有什么不同呢?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(2)
天蓬老师

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.addEventListenerdocument.addEventListener来处理页面上的事件,区别仅仅在于,不同事件模型上,处理的顺序不一样:

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

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

伊谢尔伦

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号