1、语法
var rect=el.getBoundingClientRect();
2、返回值
返回一个包含left、top、right、bottom、width、height值的矩形对象。
注:
width和height:ie9及以上支持width/height属性。
兼容ie6~ie8的width/height的写法:
return{
width:rect.right-rect.left,
height:rect.bottom-rect.top
}
3、 兼容性
pc端:
移动端:
(图片及文章参考:http://www.cnblogs.com/Songyc/p/4458570.html)
在ie7及ie7以下的html元素坐标会从(2, 2)开始算起,所以在ie7及ie7以下left和top会多出两个像素。
用 document.documentElement.clientLeft 和 document.documentElement.clientTop 做兼容
(ie7及以下document.documentElement.clientLeft = document.documentElement.clientTop=2,
而ie8及以上 document.documentElement.clientLeft = document.documentElement.clientTop=0)
完整兼容写法如下:
function getRect(el){
var rect=el.getBoundingClientRect();
var _left=document.documentElement.clientLeft;
var _top=document.documentElement.clientTop;
return{
left:rect.left-_left,
top:rect.top-_top,
right:rect.right-_left,
bottom:rect.bottom-_top,
width:rect.right-rect.left,
height:rect.bottom-rect.top
}
}