JavaScript/元素位置
来自康健生活
引言
元素在当前坐标系中的位置
获取元素在当前文档区域坐标系中的坐标,考虑 transform 等 css 属性影响其内部坐标系定位的问题。
function getPosition(element) {
const actualLeft = element.offsetLeft;
const actualTop = element.offsetTop;
const current = element.offsetParent;
// 循环直到根元素
while (current !== null) {
actualLeft += current.offsetLeft;
actualTop += current.offsetTop;
current = current.offsetParent;
}
return {
left: actualLeft,
top: actualTop
};
}
元素在当前视窗坐标系中的位置
function getPosition(element){
// 获取元素相对浏览器视窗window的左、上坐标
let {left: _x, top: _y} = element.getBoundingClientRect();
// 与 html 或 body 元素的滚动距离相加就是元素相对于文档区域 document 的坐标位置
_x += document.documentElement.scrollLeft || document.body.scrollLeft;
_y += document.documentElement.scrollTop || document.body.scrollTop;
return {
left: _x,
top: _y
};
}
No categories