我想知道如何在JavaScript中获取img和div等HTML元素的X和Y位置。
当前回答
jQuery.offset()将获取第一个元素的当前坐标,或者设置匹配元素集合中每个元素相对于文档的坐标。
其他回答
由于不同的浏览器以不同的方式呈现边框、填充、边距等。我编写了一个小函数来检索每个根元素中特定元素的顶部和左侧位置,您需要精确的维度:
function getTop(root, offset) {
var rootRect = root.getBoundingClientRect();
var offsetRect = offset.getBoundingClientRect();
return offsetRect.top - rootRect.top;
}
对于检索左侧位置,必须返回:
return offsetRect.left - rootRect.left;
正确的方法是使用element.getBoundingClientRect():
var rect = element.getBoundingClientRect();
console.log(rect.top, rect.right, rect.bottom, rect.left);
Internet Explorer一直支持这一点,只要您可能关心,它最终在CSSOM视图中被标准化。 所有其他浏览器早就采用了它。
一些浏览器还返回高度和宽度财产,尽管这是非标准的。如果您担心较旧的浏览器兼容性,请检查此答案的修订版,以获得优化的降级实现。
element.getBoundingClientRect()返回的值与视口相关。如果需要相对于另一个元素使用,只需从另一个矩形中减去一个矩形即可:
var bodyRect = document.body.getBoundingClientRect(),
elemRect = element.getBoundingClientRect(),
offset = elemRect.top - bodyRect.top;
alert('Element is ' + offset + ' vertical pixels from <body>');
我可以像element.offsetLeft或element.ooffsetTop一样。示例:document.getElementById('profileImg').offsetLeft
我想我也会把这个扔出去。我还不能在旧版浏览器中测试它,但它在前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()};
};
如果您使用jQuery,这可能是一个简单的解决方案:
<script>
var el = $("#element");
var position = el.position();
console.log( "left: " + position.left + ", top: " + position.top );
</script>