原生js獲取 一個dom元素距離頁面可視區域的位置值 -- getBoundingClientRect

getBoundingClientRect()


  • 這個方法返回一個矩形對象,包含四個屬性:left、top、right和bottom。分別表示元素各邊與頁面上邊和左邊的距離。瀏覽器

    var box=document.getElementById('box'); // 獲取元素對象

    alert(box.getBoundingClientRect().top); // 元素上邊距離頁面上邊的距離get

    alert(box.getBoundingClientRect().right); // 元素右邊距離頁面左邊的距離cli

    alert(box.getBoundingClientRect().bottom); // 元素下邊距離頁面上邊的距離gc

    alert(box.getBoundingClientRect().left); // 元素左邊距離頁面左邊的距離方法

  • 注意:IE、Firefox3+、Opera9.五、Chrome、Safari支持,在IE中,默認座標從(2,2)開始計算,致使最終距離比其餘瀏覽器多出兩個像素,咱們須要作個兼容。top

相關文章
相關標籤/搜索