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

    }

}

分別加上外邊據、內邊距、邊框和滾動條,用於測試所有瀏覽器是否一致。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



猜您在找 JavaScript中getBoundingClientRect()方法詳解 聊聊 getClientRects 和 getBoundingClientRect 方法 JavaScript 數組中的 indexOf 方法詳解 getBoundingClientRect獲取元素位置以及在Vue中的使用 JavaScript中數組Array.sort()排序方法詳解 HTML中javascript的