0


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;
标签: javascript 前端 html

本文转载自: https://blog.csdn.net/qq_43682422/article/details/129736467
版权归原作者 godlike-icy 所有, 如有侵权,请联系我们删除。

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

还没有评论