JavaScript中getBoundingClientRect()方法詳解

來源:互聯網
上載者:User

標籤:client   相容   返回   str   otto   矩形   其他   頁面   捲軸   

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

    }

}

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

JavaScript中getBoundingClientRect()方法詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.