Javascript 如何使用javascript获取html元素的x,y位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10853625/
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-24 03:14:25  来源:igfitidea点击:

How to grab the x, y position of html elements with javascript

javascripthtmldomgetelementbyid

提问by Nudier Mena

I have in my html document several div elements with certain css class and want to get x, y position of those elements, thanks in advance.

我在我的 html 文档中有几个具有特定 css 类的 div 元素,并且想要获得这些元素的 x、y 位置,在此先感谢。

回答by MaxArt

Use getBoundingClientRect: http://ejohn.org/blog/getboundingclientrect-is-awesome/

使用getBoundingClientRecthttp: //ejohn.org/blog/getboundingclientrect-is-awesome/

For example:

例如:

var div = document.getElementById("yourDiv");
var rect = div.getBoundingClientRect();
alert("Coordinates: " + rect.left + "px, " + rect.top + "px");

Remember that getBoundingClientRectgives the coordinates relative to the current viewport, which means that if you want to know the coordinates relative to the document.body, you have to add the horizontal and vertical scroll amounts (document.documentElement.scrollLeftor document.body.scrollLeftfor Firefox, and .scrollTopof course).

请记住,getBoundingClientRect给出了相对于当前视口的坐标,这意味着如果您想知道相对于 的坐标document.body,则必须添加水平和垂直滚动量(document.documentElement.scrollLeft或者document.body.scrollLeft对于 Firefox,.scrollTop当然)。

回答by jakubiszon

If I understand, you want to do this http://www.quirksmode.org/js/findpos.html

如果我明白,你想这样做http://www.quirksmode.org/js/findpos.html

回答by Flavio Cysne

The examples bellow show how to retrieve the ClientRect of an HTML Element

下面的示例显示了如何检索 HTML 元素的 ClientRect

# first tag link of this page
document.getElementsByClassName('post-taglist')[0].children[0].getClientRects()[0]
# question div
document.getElementById('question').getClientRects()[0]

With it you have acces to right, top, height, width, left and bottom attributes.

有了它,您可以访问右侧、顶部、高度、宽度、左侧和底部属性。