Javascript get element at point outside viewport

后端 未结 1 1385
时光说笑
时光说笑 2021-01-13 13:28

Is there something similar to document.elementFromPoint(x,y) that works for elements that are outside the viewport?

According to the MDN docs for document.elementFro

相关标签:
1条回答
  • 2021-01-13 14:01

    Hey I had the same issue, where if the element is not within the current bounds of the viewport elementFromPoint will return null.

    I find that you have to scroll to the element location to make it visible in the viewport and then perform the elementFromPoint.

    (function() {
      'use strict';
      var api;
      api = function(x,y) {
        var elm, scrollX, scrollY, newX, newY;
        /* stash current Window Scroll */
        scrollX = window.pageXOffset;
        scrollY = window.pageYOffset;
        /* scroll to element */
        window.scrollTo(x,y);
        /* calculate new relative element coordinates */
        newX = x - window.pageXOffset;
        newY = y - window.pageYOffset;
        /* grab the element */
        elm = this.elementFromPoint(newX,newY);
        /* revert to the previous scroll location */
        window.scrollTo(scrollX,scrollY);
        /* returned the grabbed element at the absolute coordinates */
        return elm;
      };
      this.document.elementFromAbsolutePoint = api;
    }).call(this);
    

    You can simply use this command whenever the coordinates are absolute from the pageX,pageY.

    document.elementFromAbsolutePoint(2084, 1536);
    

    This code is also on GitHub packaged into a bower component for ease of including into projects.

    https://github.com/kylewelsby/element-from-absolute-point

    Hope this helps your project.

    0 讨论(0)
提交回复
热议问题