getBoundingClientRect()方法的使用

建立了自己的博客,从今天开始,我要陆续的记录我自己学习的东西和工作中遇到的问题。
getBoundingClient()方法返回一个矩形对象,它包含4个属性:left,top,right和bottom。分别表示元素个边与页面可视区域的上边和左边的距离。要注意left和right都是元素相对于可视区域的左侧的距离,top和bottom都是元素相对于可视区域顶部的距离。

下面上代码

html中

1
<div id="box" style="width:100px;height:100px;margin:0 auto;background:red;"></div>

js中

1
2
3
4
5
var box = document.getElementById("box");//获取元素
box.getBoundingClientRect().top;//获取元素顶部与页面可视区域的顶部的距离
box.getBoundingClientRect().bottom;//获取元素底部与页面可视区域的顶部的距离
box.getBoundingClientRect().right;//获取元素右侧与页面可视区域的左侧的距离
box.getBoundingClientRect().left;//获取元素左侧与页面可视区域的左侧的距离

同时也要注意:在IE,Firefox3+,Opera9.5,Chrome,safari支持。在IE中,默认坐标从(2,2)开始计算,导致最终比其他浏览器多出两个像素。
兼容的方法:

1
2
3
4
5
6
7
8
9
10
11
function getClientRect(obj)
{
var rect = obj.getBoundingClientRect();
var c_left = document.documentElement.clientLeft;//非IE中,获取值为0,否则为2;
var c_top = document.documentElement.clientTop;//非IE中,获取值为0,否则为2;
var left = rect.left - c_left,
right = rect.right - c_left,
top = rect.top - c_top,
bottom = rect.bottom - c_top;
return {left,right,top,bottom};
}