我想知道如何在JavaScript中获取img和div等HTML元素的X和Y位置。
当前回答
我可以像element.offsetLeft或element.ooffsetTop一样。示例:document.getElementById('profileImg').offsetLeft
其他回答
这很简单,在JS中有两行:
var elem = document.getElementById("id");
alert(elem.getBoundingClientRect());
这是一个使用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) {
const rect = el.getBoundingClientRect();
return {
left: rect.left + window.scrollX,
top: rect.top + window.scrollY
};
}
使用此选项,我们可以获得X位置:
getOffset(element).left
…或Y位置:
getOffset(element).top
jQuery.offset()将获取第一个元素的当前坐标,或者设置匹配元素集合中每个元素相对于文档的坐标。
我可以像element.offsetLeft或element.ooffsetTop一样。示例:document.getElementById('profileImg').offsetLeft