Javascript在视口外的点获取元素 [英] Javascript get element at point outside viewport

查看:58
本文介绍了Javascript在视口外的点获取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有类似于document.elementFromPoint(x,y)的东西可用于视口之外的元素?

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

根据MDN文档document.elementFromPoint()( https://developer.mozilla.org/zh-CN/docs/DOM/document.elementFromPoint )

According to the MDN docs for document.elementFromPoint() (https://developer.mozilla.org/en-US/docs/DOM/document.elementFromPoint)

如果指定的点在文档的可见范围之外或任一坐标为负数,则结果为null.

If the specified point is outside the visible bounds of the document or either coordinate is negative, the result is null.

因此,很显然,如果您尝试获取超出用户视口的元素,则将无法正常工作.

So obviously it doesn't work if you're trying to grab elements beyond the user's viewport.

谢谢!

推荐答案

嘿,我遇到了同样的问题,如果该元素不在视口的当前范围内,则 elementFromPoint 将返回.

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

我发现您必须滚动到元素位置以使其在视口中可见,然后执行 elementFromPoint .

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);

只要 pageX pageY 中的坐标是绝对坐标,您就可以简单地使用此命令.

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

document.elementFromAbsolutePoint(2084, 1536);

此代码也在GitHub上打包到Bower组件中,以便于包含到项目中.

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.

这篇关于Javascript在视口外的点获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆