开发者

Element coordinates in pure Javascript

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?

开发者_如何学GoAnd I need to be able to do it in pure Javascript...


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


Use the below

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜