简体   繁体   English

将事件监听器附加到整个html文档的最佳方法

[英]Best way of attaching event listener to the whole html document

Let's consider the problem of capturing mousemove on the whole HTML document. 让我们考虑在整个HTML文档中捕获mousemove的问题。

I know four objects to which event listener can be attached: 我知道可以附加事件监听器的四个对象:

window , document , document.body , document.documentElement windowdocumentdocument.bodydocument.documentElement

After simple tests it seemed to me that attaching to any of them has the same effect. 经过简单的测试,在我看来,附加到它们中的任何一个都具有相同的效果。

$(window).on('mousemove', function(){console.log(1)})

I was wondering if there is any difference I don't know about (performance, compatibility?) 我想知道是否有任何我不知道的差异(性能,兼容性?)

There are two potential issuses with binding the event to the document.body object: 有两个可能的事件将事件绑定到document.body对象:

  • Some browsers doesn't allow accessing the body object before the content in the page has begun being parsed, so binding the event directly in the head won't work. 某些浏览器在页面中的内容开始被解析之前不允许访问body对象,因此直接在头部绑定事件将不起作用。 You need to bind it from the load or ready event, or from code inside the body. 您需要从loadready事件或body中的代码绑定它。

  • In standards compliant mode (HTML 4, XHTML, HTML5) the body element doesn't automatically cover the entire window. 在标准兼容模式(HTML 4,XHTML,HTML5)中,body元素不会自动覆盖整个窗口。 It will only be as large as it needs to contain the content, and if it has a margin that is not covered by the body element. 它只会包含内容所需的大小,如果它有一个未被body元素覆盖的边距。

Also, if the page contains frames, then this won't work. 此外,如果页面包含框架,那么这将不起作用。 In that case, follow steps explained here . 在这种情况下,请按照此处说明的步骤进

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM