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

假装没事ソ 提交于 2020-07-17 10:47:27

问题


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.


回答1:


Use 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).




回答2:


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




回答3:


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

# 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.



来源:https://stackoverflow.com/questions/10853625/how-to-grab-the-x-y-position-of-html-elements-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!