window.document.addEventListener vs window.addEventListener [英] window.document.addEventListener vs window.addEventListener

查看:232
本文介绍了window.document.addEventListener vs window.addEventListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

window.document.addEventListener = function(event){...}

window.addEventListener = function(event){...}

这两行代码有什么区别?我得到那个窗口,文档对象是两个具有不同属性的不同对象,并且此网站为差异提供了良好的视觉指导。我仍然没有看到这两行代码之间的区别。

What is the difference between these two lines of code? I get that window and document object are two different objects with different properties and this site provides a good visual guide to the difference. Still I don't see the difference between what these two lines of code are doing.

进一步说明:做这样的事情有什么区别:
window.addEventListener('mousemove',function(event){...});
并执行类似窗口的操作。 document.addEventListener('mousemove',function(event){...});

To further clarify: what is the difference in doing something like this: window.addEventListener('mousemove', function (event) {...}); and doing something like this window.document.addEventListener('mousemove', function (event) {...});?

推荐答案

大多数DOM对象以及窗口本身都有 addEventListener 方法。事件在事件开始的元素及其祖先上冒泡并触发事件侦听器。

There are addEventListener methods on most DOM objects, as well as on the window itself. Events bubble and trigger event listeners on the element on which the event starts and its ancestors.

这两段代码在不同级别上覆盖 addEventListener

如果您要调用原始方法,那么很少(如果有的话)使您调用它们中的哪些对象产生任何差异。如果你要进行比较会有所不同,例如:

If you were to call the original method, it would rarely (if ever) make any difference which of those objects you called it on. It would make a difference if you were to compare, for example:

window.addEventListener('click', handler);
document.querySelector('button', handler);

因为一个人会捕获文档中的所有点击而另一个只捕获第一个按钮上的那些元素。

Since one would capture all the clicks in the document and the other would only capture those on the first button element.

这篇关于window.document.addEventListener vs window.addEventListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆