Element coordinates in pure Javascript

后端 未结 3 1747
梦谈多话
梦谈多话 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

    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!

提交回复
热议问题