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


当前回答

这很简单,在JS中有两行:

var elem = document.getElementById("id");    
alert(elem.getBoundingClientRect());

其他回答

我可以像element.offsetLeft或element.ooffsetTop一样。示例:document.getElementById('profileImg').offsetLeft

您可以将两个财产添加到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/

如果使用jQuery,维度插件非常出色,可以让您精确地指定所需内容。

e.g.

相对位置,绝对位置,无填充的绝对位置,有填充。。。

继续下去,让我们说你可以用它做很多事情。

另外,使用jQuery的好处是它的文件大小很小,使用起来很方便,以后如果没有它,就不会返回JavaScript。

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

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

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

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

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

这是一个使用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));
}