Javascript 使用 jQuery 在特定位置查找元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3942776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:45:46  来源:igfitidea点击:

Using jQuery to find an element at a particular position?

javascriptjquery

提问by Thomas John

Is there a method in jQuery to select an element located at a particular position?

jQuery 中是否有一种方法可以选择位于特定位置的元素?

For example, can I select the element that is located at left:100 and top:300 in absolute position?

例如,我可以选择绝对位置位于 left:100 和 top:300 的元素吗?

It would be nice if I could select an element located in a range of positions, for example, select the element that is located left: 100 - 150 px top 200 - 280px.

如果我可以选择位于一系列位置的元素,那就太好了,例如,选择位于左侧的元素:100 - 150 px top 200 - 280px。

回答by jAndy

You are looking for the .elementFromPoint()JavaScript/DOM method.

您正在寻找.elementFromPoint()JavaScript/DOM 方法。

var elem = document.elementFromPoint(100, 100) // x, y

That returns a DOM node, which of course then can be wrapped into a jQuery object:

这将返回 a DOM node,当然可以将其包装到 jQuery 对象中:

$(elem).remove(); // for instance

I'm not that aware about the cross-browser compatibility and I would like some guys who know better to edit this post or write a comment about it.

我不太了解跨浏览器的兼容性,我希望一些更了解的人编辑这篇文章或写一篇评论。

Reference: .elementFromPoint()

参考:.elementFromPoint()

Example Link: http://www.jsfiddle.net/YjC6y/22/

示例链接:http: //www.jsfiddle.net/YjC6y/22/

回答by Cees Timmerman

Provided you know the exact coordinates relative to the document:

如果您知道相对于文档的确切坐标:

function getElsAt(top, left){
    return $("body")
               .find("*")
               .filter(function() {
                           return $(this).offset().top == top 
                                    && $(this).offset().left == left;
               });
}

The other answer stops at the first overlay.

另一个答案在第一个叠加层处停止。