我想知道如何在JavaScript中获取img和div等HTML元素的X和Y位置。


当前回答

这是一个使用vanilla JS递归迭代element.offsetTop和element.ooffsetParent的现代1行代码:

功能:

getTop = el => el.offsetTop + (el.offsetParent && getTop(el.offsetParent))

用法:

const el = document.querySelector('#div_id');
const elTop = getTop(el)

优势:

无论当前滚动位置如何,始终返回绝对垂直偏移。


传统语法:

function getTop(el) {
  return el.offsetTop + (el.offsetParent && getTop(el.offsetParent));
}

其他回答

为了获得元素的精确偏移量,库会进行一定的长度。这里有一个简单的函数,它在我尝试过的所有情况下都能完成任务。

function getOffset( el ) {
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.offsetParent;
    }
    return { top: _y, left: _x };
}
var x = getOffset( document.getElementById('yourElId') ).left; 

要获得元素的总偏移量,可以递归地对所有父偏移量求和:

function getParentOffset(el): number {
if (el.offsetParent) {
    return el.offsetParent.offsetTop + getParentOffset(el.offsetParent);
} else {
    return 0;
}
}

使用该实用函数,dom元素的总顶部偏移量为:

el.offsetTop + getParentOffset(el);

如果您只想在javascript中完成,这里有一些使用getBoundingClientRect()的单行程序

window.scrollY + document.querySelector('#elementId').getBoundingClientRect().top // Y

window.scrollX + document.querySelector('#elementId').getBoundingClientRect().left // X

第一行将返回offsetTop,比如相对于文档的Y。第二行将返回offsetLeft,比如相对于文档的X。

getBoundingClientRect()是一个javascript函数,它返回元素相对于窗口视口的位置。

您可以将两个财产添加到Element.protype中,以获得任何元素的顶部/左侧。

Object.defineProperty( Element.prototype, 'documentOffsetTop', {
    get: function () { 
        return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop : 0 );
    }
} );

Object.defineProperty( Element.prototype, 'documentOffsetLeft', {
    get: function () { 
        return this.offsetLeft + ( this.offsetParent ? this.offsetParent.documentOffsetLeft : 0 );
    }
} );

这被称为:

var x = document.getElementById( 'myDiv' ).documentOffsetLeft;

下面是一个将结果与jQuery的offset().top和.left进行比较的演示:http://jsfiddle.net/ThinkingStiff/3G7EZ/

我想我也会把这个扔出去。我还不能在旧版浏览器中测试它,但它在前3名中的最新版本中运行。:)

Element.prototype.getOffsetTop = function() {
    return ( this.parentElement )? this.offsetTop + this.parentElement.getOffsetTop(): this.offsetTop;
};
Element.prototype.getOffsetLeft = function() {
    return ( this.parentElement )? this.offsetLeft + this.parentElement.getOffsetLeft(): this.offsetLeft;
};
Element.prototype.getOffset = function() {
    return {'left':this.getOffsetLeft(),'top':this.getOffsetTop()};
};