如何使用javascript捕获html元素的x,y位置
我在html文档中有一些具有某些CSS类的div元素,并想获得这些元素的x,y位置,请先感谢。
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.
使用 getBoundingClientRect
:
http://ejohn.org/blog/getboundingclientrect-is-awesome/
例如:
var div = document.getElementById("yourDiv");
var rect = div.getBoundingClientRect();
alert("Coordinates: " + rect.left + "px, " + rect.top + "px");
记住 getBoundingClientRect
给出坐标相对于当前视口,这意味着,如果您想知道相对于 document.body
的坐标,则必须添加水平和垂直滚动金额(对于Firefox,为 document.documentElement.scrollLeft
或 document.body.scrollLeft
。 scrollTop 当然。)
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).