📜  document.elementfrompoint (1)

📅  最后修改于: 2023-12-03 15:30:32.803000             🧑  作者: Mango

document.elementFromPoint

The document.elementFromPoint method is a useful function for identifying the element at a specified point on the web page. This method takes in two arguments, the x and y coordinates of the point, and returns the topmost element at that position.

Syntax
element = document.elementFromPoint(x, y);

Parameters:

  • x: The x-coordinate of the point.
  • y: The y-coordinate of the point.

Return value:

  • null: If no element exists at the specified point.
  • Element: The topmost element at the specified point.
Example
<body>
  <div id="outer">
    <div id="inner">
      <p id="message">Click anywhere on the page</p>
    </div>
  </div>
  <script>
    document.addEventListener('click', function(event) {
      var x = event.clientX;
      var y = event.clientY;
      var element = document.elementFromPoint(x, y);
      console.log('Clicked element:', element);
    });
  </script>
</body>

In this example, whenever the user clicks anywhere on the page, the document.elementFromPoint method is called with the x and y coordinates of the click event. The topmost element at that point is then logged to the console.

Considerations
  • The coordinates passed to document.elementFromPoint are relative to the viewport, not the document. If you need to get the position of a child element relative to the document, you can use the offsetLeft and offsetTop properties.
  • This method will not return elements that are hidden or have a pointer-events CSS property set to none.
  • If the x and y coordinates are outside the boundaries of the viewport, elementFromPoint will return null.
Conclusion

In summary, document.elementFromPoint is a powerful method that can help you get information about elements on a web page. Whether you're building a complex application or just need to grab information from the page, elementFromPoint is an important tool to have in your JavaScript arsenal.