最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - window.document.addEventListener vs window.addEventListener - Stack Overflow

programmeradmin0浏览0评论

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.

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) {...});?

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.

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) {...});?

Share Improve this question edited Oct 13, 2015 at 18:54 isaac9A asked Oct 13, 2015 at 18:46 isaac9Aisaac9A 9034 gold badges12 silver badges31 bronze badges 1
  • Possible duplicate of Difference between document.addEventListener and window.addEventListener? – kano Commented Dec 5, 2018 at 13:19
Add a ment  | 

1 Answer 1

Reset to default 3

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.

The two pieces of code there overwrite the addEventListener on different levels.

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 pare, 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.

发布评论

评论列表(0)

  1. 暂无评论