Nud*_*ena 7 html javascript dom getelementbyid
我在我的html文档中有几个具有某些css类的div元素,并希望获得这些元素的x,y位置,在此先感谢.
Max*_*Art 20
使用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");
Run Code Online (Sandbox Code Playgroud)
请记住,getBoundingClientRect给出相对于当前视口的坐标,这意味着如果您想知道相对于该坐标的坐标document.body,则必须添加水平和垂直滚动量(document.documentElement.scrollLeft或者document.body.scrollLeft对于Firefox,.scrollTop当然还有).