admin管理员组文章数量:1323336
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.elementFromPoint() (.elementFromPoint)
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.
Thanks!
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.elementFromPoint() (https://developer.mozilla/en-US/docs/DOM/document.elementFromPoint)
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.
Thanks!
Share Improve this question asked Oct 31, 2013 at 20:03 nickbnickb 952 silver badges5 bronze badges 1- This feature request is filed as w3/Bugs/Public/show_bug.cgi?id=20328 (no activity for 5 years though..) – Nickolay Commented Dec 3, 2017 at 20:54
1 Answer
Reset to default 11Hey 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 mand whenever the coordinates are absolute from the pageX
,pageY
.
document.elementFromAbsolutePoint(2084, 1536);
This code is also on GitHub packaged into a bower ponent for ease of including into projects.
https://github./kylewelsby/element-from-absolute-point
Hope this helps your project.
本文标签: Javascript get element at point outside viewportStack Overflow
版权声明:本文标题:Javascript get element at point outside viewport - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742136660a2422400.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论