javascript
JavaScript中getBoundingClientRect()方法详解
JavaScript中getBoundingClientRect()方法詳解
getBoundingClientRect()
這個方法返回一個矩形對象,包含四個屬性:left、top、right和bottom。分別表示元素各邊與頁面上邊和左邊的距離。
?
var box=document.getElementById('box'); ? ? ????// 獲取元素
alert(box.getBoundingClientRect().top); ? ? ? ? // 元素上邊距離頁面上邊的距離
alert(box.getBoundingClientRect().right); ? ? ? // 元素右邊距離頁面左邊的距離
alert(box.getBoundingClientRect().bottom); ?????// 元素下邊距離頁面上邊的距離
alert(box.getBoundingClientRect().left); ? ? ? ?// 元素左邊距離頁面左邊的距離
?
注意:IE、Firefox3+、Opera9.5、Chrome、Safari支持,在IE中,默認坐標從(2,2)開始計算,導致最終距離比其他瀏覽器多出兩個像素,我們需要做個兼容。
?
document.documentElement.clientTop; ?// 非IE為0,IE為2
document.documentElement.clientLeft; // 非IE為0,IE為2
functiongGetRect (element) {
????var rect = element.getBoundingClientRect();
????var top = document.documentElement.clientTop;
????var left= document.documentElement.clientLeft;
????return{
????????top????: ? rect.top - top,
????????bottom?: ? rect.bottom - top,
????????left???: ??rect.left - left,
????????right ?: ? rect.right - left
????}
}
分別加上外邊據、內邊距、邊框和滾動條,用于測試所有瀏覽器是否一致。
轉載于:https://www.cnblogs.com/nuoyiamy/p/5318314.html
總結
以上是生活随笔為你收集整理的JavaScript中getBoundingClientRect()方法详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DUMP文件分析6:简单的堆破坏示例
- 下一篇: 1-9:学习shell之权限