getBoundingClientRect()方法的理解与使用
getBoundingClientRect()方法返回一个的是一个对象,对象下的四个属性:left、top、right和bottom分别表示元素各边与页面上边和左边的距离。
例子:
var box=document.getElementById('box'); // 获取元素
box.getBoundingClientRect().top; // 元素上边距离页面上边的距离
box.getBoundingClientRect().right; // 元素右边距离页面左边的距离
box.getBoundingClientRect().bottom; // 元素下边距离页面上边的距离
box.getBoundingClientRect().left; // 元素左边距离页面左边的距离
getBoundingClientRect()方法图例
注意:在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
}