Element coordinates in pure Javascript

后端 未结 3 1743
梦谈多话
梦谈多话 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;
    }
    
    0 讨论(0)
  • 2021-01-13 08:47

    Going off of ShankarSangoli's post, it can be expanded this way. Get the difference between the parent (container) and the child (element in question):

    var parentOffsetTop = document.getElementById("parentId").offsetTop;
    var parentOffsetLeft = document.getElementById("parentId").offsetLeft;
    var childOffsetTop = document.getElementById("childId").offsetTop;
    var childOffsetLeft = document.getElementById("childId").offsetLeft;
    
    var xOffset = parentOffsetLeft - childOffsetLeft;
    var yOffset = parentOffsetTop - childOffsetTop;
    

    EDIT: seems I was mistaken, offsetLeft and offsetTop are based off of the parent anyway. You do not need to do this manually!

    0 讨论(0)
  • 2021-01-13 08:58

    Use the below

    document.getElementById("elementId").offsetTop;
    document.getElementById("elementId").offsetLeft;
    
    0 讨论(0)
提交回复
热议问题