我想知道如何在JavaScript中获取img和div等HTML元素的X和Y位置。
当前回答
我想我也会把这个扔出去。我还不能在旧版浏览器中测试它,但它在前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()};
};
其他回答
使用JavaScript框架可能会更好地为您服务,该框架具有以独立于浏览器的方式返回此类信息(以及更多信息!)的功能。以下是一些:
原型jQuery框架YUI(雅虎)
使用这些框架,您可以执行以下操作:$('id-of-img').top以获得图像的y像素坐标。
我想我也会把这个扔出去。我还不能在旧版浏览器中测试它,但它在前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()};
};
经过大量研究和测试,这似乎奏效了
function getPosition(e) {
var isNotFirefox = (navigator.userAgent.toLowerCase().indexOf('firefox') == -1);
var x = 0, y = 0;
while (e) {
x += e.offsetLeft - e.scrollLeft + (isNotFirefox ? e.clientLeft : 0);
y += e.offsetTop - e.scrollTop + (isNotFirefox ? e.clientTop : 0);
e = e.offsetParent;
}
return { x: x + window.scrollX, y: y + window.scrollY };
}
看见http://jsbin.com/xuvovalifo/edit?html,js,输出
这是一个使用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));
}
jQuery.offset()将获取第一个元素的当前坐标,或者设置匹配元素集合中每个元素相对于文档的坐标。