Element coordinates in pure Javascript

后端 未结 3 1748
梦谈多话
梦谈多话 2021-01-13 08:14

Say that I have an element inside a div (or any other containing element, or perhaps just in the body of the document). How do I get the (x,y) coordinates of that element, r

3条回答
  •  太阳男子
    2021-01-13 08:47

    The offsetTop and offsetLeft properties are relative to offsetParent so you can get an element's position relative to its parent for free. If you want the position relative to the entire body then you need to traverse the offsetParent chain and sum the values.

    The following function accomplishes this:

    function findPos(obj) {
        var curleft = 0, curtop = 0;
        if (obj.offsetParent) {
            do {
                curleft += obj.offsetLeft;
                curtop += obj.offsetTop;
            } while (obj = obj.offsetParent);
            return { x: curleft, y: curtop };
        }
        return undefined;
    }
    

提交回复
热议问题