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元素坐標(biāo)會從(0,0)開始算起,而IE7及IE7以下的html元素坐標(biāo)會從(2,2)開始算起,IE8已修復(fù)這個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;