简体   繁体   中英

Best way of attaching event listener to the whole html document

Let's consider the problem of capturing mousemove on the whole HTML document.

I know four objects to which event listener can be attached:

window , document , document.body , document.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:

  • 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. You need to bind it from the load or ready event, or from code inside the body.

  • In standards compliant mode (HTML 4, XHTML, HTML5) the body element doesn't automatically cover the entire window. 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.

Also, if the page contains frames, then this won't work. In that case, follow steps explained here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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