是否有类似于document.elementFromPoint(x,y)的东西适用于视口之外的元素?
根据MDN文档document.elementFromPoint()(https://developer.mozilla.org/en-US/docs/DOM/document.elementFromPoint)
如果指定的点位于文档的可见边界之外,或者任一坐标为负,则结果为null.
显然,如果你试图抓住用户视口之外的元素,它就不起作用了.
谢谢!
嘿我有同样的问题,如果元素不在视口的当前边界内elementFromPoint将返回null.
我发现你必须滚动到元素位置,使其在视口中可见,然后执行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);
Run Code Online (Sandbox Code Playgroud)
只要坐标是绝对的pageX,你就可以简单地使用这个命令pageY.
document.elementFromAbsolutePoint(2084, 1536);
Run Code Online (Sandbox Code Playgroud)
此代码也在GitHub上打包成一个凉亭组件,以便于包含到项目中.
https://github.com/kylewelsby/element-from-absolute-point
希望这有助于您的项目.
| 归档时间: |
|
| 查看次数: |
1113 次 |
| 最近记录: |