Why document.elementFromPoint returns null for elements outside the visible document

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

I noticed that document.elementFromPoint returns null for any point that is initially outside the visible document, and also after scrolling in the view.

An easy way to check this in Chrome (ctrl-shift-i β†’ scripts β†’ 'watch expressions') (make sure the page height is narrowed to less than 1000 pixels)

EDIT: therefore makes sense according to docs

  • always returns null for points outside the visible region
  • x and y refer to the upper left and right screens of the visible screen.

I failed to fulfill both assumptions,

+6
javascript google-chrome
source share
2 answers

It makes sense that it does not return any element when you specify a point outside the window. It returns the elements that are visible at this point, and not the elements that would be visible there if the window had a different size. Note that resizing the window can cause the elements to move, so you won’t get a consistent answer if it returned elements that might appear at that point.

No matter how you scroll through the contents of the window, the dot outside the window is outside the window.

+2
source share

So, you answered your own question: document.elementFromPoint works in the view coordinate, not in the document. So all you have to do is add scroll compensation.

The following code was developed for me:

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

Or, if you are listening to an event that would be as follows:

 document.elementFromPoint(e.pageX - window.pageXOffset, e.pageY - window.pageYOffset); 
+38
source share

All Articles