我想知道如何在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()};
};
其他回答
这是一个使用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()不同,也可以在iframes中使用)。看起来webkit有点不同的行为。
基于meouw的评论:
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;
// chrome/safari
if ($.browser.webkit) {
el = el.parentNode;
} else {
// firefox/IE
el = el.offsetParent;
}
}
return { top: _y, left: _x };
}
如果使用jQuery,维度插件非常出色,可以让您精确地指定所需内容。
e.g.
相对位置,绝对位置,无填充的绝对位置,有填充。。。
继续下去,让我们说你可以用它做很多事情。
另外,使用jQuery的好处是它的文件大小很小,使用起来很方便,以后如果没有它,就不会返回JavaScript。
小与小的区别
function getPosition( 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 };
}
查看坐标示例:http://javascript.info/tutorial/coordinates
正确的方法是使用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>');
推荐文章
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- Twitter Bootstrap 3 Sticky Footer
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- CSS在特定的“内联块”项之前/之后换行
- 很好的初学者教程socket.io?
- 内嵌CSS有什么不好?
- 点击下载Href图片链接
- HtmlSpecialChars在JavaScript中等价于什么?
- 我如何删除背景图像在css?
- 如何克服HTML表单嵌套的限制?