Element coordinates in pure Javascript

ⅰ亾dé卋堺 提交于 2019-12-01 04:09:27

问题


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, relative to its container?

And I need to be able to do it in pure Javascript...


回答1:


Use the below

document.getElementById("elementId").offsetTop;
document.getElementById("elementId").offsetLeft;



回答2:


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;
}



回答3:


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!



来源:https://stackoverflow.com/questions/6780376/element-coordinates-in-pure-javascript

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