原文出处:https://blog.csdn.net/a271720559/article/details/81278345
我们在做网页是有时会需要用到绝对定位这时需要判定元素离页面的距离。今天我们来看看怎么获取元素距离页面的top、left、right、bottom。
代码:
var el = document.getElementById('list-content'); // 元素
function getElemDis(el) {
var tp = document.documentElement.clientTop,
lt = document.documentElement.clientLeft,
rect = el.getBoundingClientRect();
return {
top: rect.top - tp,
right: rect.right - lt,
bottom: rect.bottom - tp,
left: rect.left - lt
}
}
我们直接用元素的getBoundingClientRect可以获取元素距离页面的距离。top和bottom则需要减去 html元素对象的上边框的宽度即clientTop而left和right则需减去clientLeft。