开发者

Why does document.elementFromPoint return null for elements outside visible document

开发者 https://www.devze.com 2023-02-16 01:42 出处:网络
Why does document.elementFromPoint(500,1000) here return null if that pixel is located outside the visible document when the document loads?

Why does document.elementFromPoint(500,1000) here return null if that pixel is located outside the visible document when the document loads?

I've noticed docu开发者_如何学运维ment.elementFromPoint returns null for any point that is initially outside the visible document, as well as after it is scrolled into view.

A simple way to test this is in Chrome (ctrl-shift-i -> scripts -> 'watch expressions') (ensure that the page height is narrowed to less than 1000 pixels)

EDIT: so it does make sense, as per docs

  1. always returns null for points outside visible area
  2. x and y are relative to the top left and right of visible screen

I failed on both assumptions,


So you kinda answered your own question: document.elementFromPoint works in the viewport coordinate rather than document. So all you need to do is to add a scroll compensation.

The following code worked out for me:

document.elementFromPoint(X - window.pageXOffset, Y - window.pageYOffset);

Or if you are listening for an event that would be:

document.elementFromPoint(e.pageX - window.pageXOffset, e.pageY - window.pageYOffset);


It makes sense that it returns no element when you specify a point outside the window. It returns elements that are visible at that point, not elements that would be visible there if the window had a different size. Consider that changing the size of the window may cause elements to move, so you wouldn't get a consistent answer if it did return elements that might be displayed at that point.

Regardless how you scroll the content in the window, a point outside the window is still outside the window.

0

精彩评论

暂无评论...
验证码 换一张
取 消