js获取元素到可视区的距离/浏览器窗口滚动距离/元素距离浏览器顶部距离

1. js获取元素距离可视区的各种距离

const box=document.getElementById('box') // 获取元素
 
const ct = box.getBoundingClientRect().top // 元素上边距离页面可视区上边的距离
 
const cr = box.getBoundingClientRect().right // 元素右边距离页面可视区左边的距离
 
const cb = box.getBoundingClientRect().bottom // 元素下边距离页面可视区上边的距离
 
const cl = box.getBoundingClientRect().left // 元素左边距离页面可视区左边的距离

2. js获取浏览器窗口滚动距离

// 浏览器滚动距离
const dt = document.documentElement.scrollTop || document.body.scrollTop;

3. js获取元素实际距离页面距离(包括滚动距离)

(1).如果父辈元素中有定位的元素,那么就返回距离当前元素最近的定位元素边缘的距离。
(2).如果父辈元素中没有定位元素,那么就返回相对于body边缘距离。

有些限制,对于滚动父元素设置为scroll:hidden时不生效。

 const box = document.getElementById('box')
 // 元素实际距离页面顶部距离
 const bt = box.offsetTop;
 // 元素实际距离页面左边距离
 const bl = box.offsetLeft;
 // 元素实际距离页面右边距离
 const br = box.offsetRight;
 // 元素实际距离页面底部距离
 const bb = box.offsetBottom;

猜你喜欢

转载自blog.csdn.net/qq_43682422/article/details/129736467