getBoundingClientRect用于获取某个元素相对于视窗的位置集合。集合中有top, right, bottom, left等属性。
262132219001037.jpg
Jquery访问:
$('#m-price')[0].getBoundingClientRect()
Js访问:
document.getElementById('m-price-calculate').getBoundingClientRect()
返回元素:
{
bottom: 553, //元素下边到视窗上边的距离;
height: 553, //元素高度,ie9以上支持
left: 840, //元素左边到视窗左边的距离;
right: 1190, //元素右边到视窗左边的距离;
top: 0, //元素上边到视窗上边的距离
width: 350 //元素宽度,ie9以上支持
}
对于height,width IE6 ~ IE8 下兼容写法:
var rectWidth = rectObject.right - rectObject.left,
rectHeight = rectObject.bottom - rectObject.top;
IE兼容性问题:在ie7及ie7以下left和top会多出两个像素。
原因:正常浏览器html元素坐标会从(0,0)开始算起,而IE7及IE7以下的html元素坐标会从(2,2)开始算起,IE8已修复这个bug
兼容写法:
var rectLeft = rectObject.left - document.documentElement.clientLeft || 2,
rectRight = rectObject.right - document.documentElement.clientLeft || 2,
rectBottom = rectObject.bottom - document.documentElement.clientTop || 2,
rectTop = rectObject.top - document.documentElement.clientTop || 2;