getBoundingClientRect()
這個方法返回一個矩形對象虱黄,包含四個屬性:left悦即、top、right和bottom橱乱。分別表示元素各邊與頁面上邊和左邊的距離辜梳。
var box=document.getElementById('box'); // 獲取元素
box.getBoundingClientRect().top; // 元素上邊距離頁面上邊的距離
box.getBoundingClientRect().right; // 元素右邊距離頁面左邊的距離
box.getBoundingClientRect().bottom; // 元素下邊距離頁面上邊的距離
box.getBoundingClientRect().left; // 元素左邊距離頁面左邊的距離
圖例
注意:IE、Firefox3+泳叠、Opera9.5作瞄、Chrome、Safari支持危纫,在IE中宗挥,默認(rèn)坐標(biāo)從(2,2)開始計算乌庶,導(dǎo)致最終距離比其他瀏覽器多出兩個像素,我們需要做個兼容契耿。
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
}
}
分別加上外邊據(jù)搪桂、內(nèi)邊距透敌、邊框和滾動條,用于測試所有瀏覽器是否一致踢械。