?getBoundingClientRect()方法的理解與使用
getBoundingClientRect()方法返回一個的是一個對象院喜,對象下的四個屬性:left烟央、top摄凡、right和bottom分別表示元素各邊與頁面上邊和左邊的距離蝎宇。
例子:
????var box=document.getElementById('box');? ? ? ? // 獲取元素
????box.getBoundingClientRect().top;? ? ? ? // 元素上邊距離頁面上邊的距離
????box.getBoundingClientRect().right;? ? ? // 元素右邊距離頁面左邊的距離
????box.getBoundingClientRect().bottom;? ? ? // 元素下邊距離頁面上邊的距離
????box.getBoundingClientRect().left;? ? ? ? // 元素左邊距離頁面左邊的距離
注意:在IE7中徽龟,默認坐標從(2,2)開始計算贤旷,即有默認的兩個像素的距離广料,導致最終距離比其他瀏覽器多出兩個像素,所以需要對其進行兼容處理遮晚,兼容方法如下:
//因為left和top都是兩個像素差性昭,所以只獲取一個就可以
function?getRect(obj){
????var?rect?=?obj.getBoundingClientRect();
????var?w?=?document.documentElement.clientLeft;//獲取兩個像素差
????return?{
????????left : rect.left?-?w,
????????right : rect.right?-?w,
????????top? :? rect.top?-?w,
????????bottom : rect.bottom?-?w
????}
}