獲取元素在頁面中位置 getBoundingClientRect()

DOM 原生方法getBoundingClientRect()獲取元素相對視口位置

  1. DOMRect 對象包含了一組用於描述邊框的只讀屬性——left、top、right和bottom,單位爲像素。除了 width 和 height 外的屬性都是相對於視口的左上角位置而言的
  2. 當計算邊界矩形時,會考慮視口區域(或其餘可滾動元素)內的滾動操做,也就是說,當滾動位置發生了改變,top和left屬性值就會隨之當即發生變化(所以,它們的值是相對於視口的,而不是絕對的)。若是你須要得到相對於整個網頁左上角定位的屬性值,那麼只要給top、left屬性值加上當前的滾動位置(經過window.scrollX和window.scrollY),這樣就能夠獲取與當前的滾動位置無關的值。
<div id="box"></div> <style> body{ margin: 0; padding: 0 } #box { position: absolute; width: 100px; height: 100px; background-color: #ccc; margin: 0; padding: 0; border: 2px solid #000; top:20px; left: 20px } </style> <script> var oBox = document.getElementById("box"); console.log(oBox.getBoundingClientRect()); // 打印結果 // bottom: 124 頂部距離盒子底部的距離(包括bordder) // height: 104 盒子高度() // left: 20 盒子左邊距離視口左邊的距離 // right: 124 盒子右邊距離視口左側的距離 // top: 20 盒子頂部距離視口頂部的距離 // width: 104 盒子的寬度 </script> <div id="box"></div> <style> body{ margin: 0; padding: 0 } #box { position: absolute; width: 100px; height: 100px; background-color: #ccc; margin: 0; padding: 0; border: 2px solid #000; top:20px; left: 20px } </style> <script> var oBox = document.getElementById("box"); console.log(oBox.getBoundingClientRect()); // 打印結果 // bottom: 124 頂部距離盒子底部的距離(包括bordder) // height: 104 盒子高度() // left: 20 盒子左邊距離視口左邊的距離 // right: 124 盒子右邊距離視口左側的距離 // top: 20 盒子頂部距離視口頂部的距離 // width: 104 盒子的寬度 </script>
相關文章
相關標籤/搜索