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

后端 未结 3 2128
臣服心动
臣服心动 2021-02-15 17:08

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.

3条回答
  •  我在风中等你
    2021-02-15 17:26

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

提交回复
热议问题