getBoundingClientRect()
是 JavaScript
中用于获取 DOM
元素位置和尺寸的原生方法,返回一个包含 top、right、bottom、left、width、height
属性的 DOMRect
对象
下面看一个例子
<div id="div"></div>
这个div
元素设置margin-top
为1000px
,距离页面顶部距离就是1000px
#div {
width: 100px;
height: 100px;
background-color: red;
margin-top:1000px;
border: 10px solid #ccc;
}
getBoundingClientRect.png
如上图所示,利用getBoundingClientRect
来获取div
元素距离浏览器窗口上下左右的距离,和自身的宽度和高度,距离浏览器窗口的距离会随着浏览器滚动条滚动会改变
const oDiv = document.getElementById('div');
const rect = oDiv.getBoundingClientRect();
console.log("元素左边界相对于视口的 x 坐标 ===== ", rect.x); // 元素左边界相对于视口的 x 坐标
console.log("元素上边界相对于视口的 y 坐标 ===== ", rect.y); // 元素上边界相对于视口的 y 坐标
console.log("元素的宽度 ===== ", rect.width); // 元素的宽度
console.log("元素的高度 ===== ", rect.height); // 元素的高度
console.log("元素上边界相对于视口顶部的距离 ===== ", rect.top); // 元素上边界相对于视口顶部的距离
console.log("元素右边界相对于视口左侧的距离 = x + width ===== ", rect.right); // 元素右边界相对于视口左侧的距离 = x + width
console.log("元素下边界相对于视口顶部的距离 = y + hight ===== ", rect.bottom); // 元素下边界相对于视口顶部的距离 = y + hight
console.log("元素左边界相对于视口左侧的距离 ===== ", rect.left); // 元素左边界相对于视口左侧的距离
当浏览器滚动时,获取元素到文档顶部的距离(注意这里不是距离浏览器窗口的距离),可以利用浏览器滚动的距离加上元素距离窗口的距离,就可以获取到元素到文档顶部的距离
window.onscroll = function () {
const oDiv = document.getElementById('div');
const rect = oDiv.getBoundingClientRect();
const oDivTop = rect.top + document.documentElement.scrollTop;
console.log(oDivTop); // 1000
}