<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> <style type="text/css"> * { padding: 0px; margin: 0px; } #main { width: 300px; height: 200px; background: red; margin-left: 300px; margin-top: 100px; } </style> <script type="text/javascript"> window.onload = function() { var a = document.getElementById("main").getBoundingClientRect(); console.log(a) } </script> </head> <body> <div id="main"> </div> </body> </html>
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
}
}
分別加上外邊據、內邊距、邊框和滾動條,用於測試所有瀏覽器是否一致。