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
How to grab the x, y position of html elements with javascript
提问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/
使用getBoundingClientRect
:http:
//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 getBoundingClientRect
gives 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.scrollLeft
or document.body.scrollLeft
for Firefox, and .scrollTop
of 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.
有了它,您可以访问右侧、顶部、高度、宽度、左侧和底部属性。