getBoundingClientRect() 是 JavaScript 中用于獲取 DOM 元素位置和尺寸的原生方法,返回一個包含 top、right、bottom、left、width、height 屬性的 DOMRect 對象
下面看一個例子
<div id="div"></div>
這個div 元素設(shè)置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 坐標(biāo) ===== ", rect.x); // 元素左邊界相對于視口的 x 坐標(biāo)
console.log("元素上邊界相對于視口的 y 坐標(biāo) ===== ", rect.y); // 元素上邊界相對于視口的 y 坐標(biāo)
console.log("元素的寬度 ===== ", rect.width); // 元素的寬度
console.log("元素的高度 ===== ", rect.height); // 元素的高度
console.log("元素上邊界相對于視口頂部的距離 ===== ", rect.top); // 元素上邊界相對于視口頂部的距離
console.log("元素右邊界相對于視口左側(cè)的距離 = x + width ===== ", rect.right); // 元素右邊界相對于視口左側(cè)的距離 = x + width
console.log("元素下邊界相對于視口頂部的距離 = y + hight ===== ", rect.bottom); // 元素下邊界相對于視口頂部的距離 = y + hight
console.log("元素左邊界相對于視口左側(cè)的距離 ===== ", rect.left); // 元素左邊界相對于視口左側(cè)的距離
當(dāng)瀏覽器滾動時,獲取元素到文檔頂部的距離(注意這里不是距離瀏覽器窗口的距離),可以利用瀏覽器滾動的距離加上元素距離窗口的距離,就可以獲取到元素到文檔頂部的距離
window.onscroll = function () {
const oDiv = document.getElementById('div');
const rect = oDiv.getBoundingClientRect();
const oDivTop = rect.top + document.documentElement.scrollTop;
console.log(oDivTop); // 1000
}