getBoundingClientRect计算页面元素的offsetLeft、offsetTop
网上很流行的方法,不用框架时:
function getOffsetPosition(element){
var posTop = 0, posLeft = 0;
do {
posTop += element.offsetTop || 0;
posLeft += element.offsetLeft || 0;
element = element.offsetParent;
} while (element);
return [posLeft, posTop];
}
firefox中到某些元素的offsetTop的值不对,反复测试发现和其父元素定位方式有关系,父元素用fixed定位,得到的offsetTop并没有加documentElement.scrollTop的值。如果documentElement有getBoundingClientRect方法,它用getBoundingClientRect去计算offset,要得到精确地offset就需要考虑元素是否表格单元格、父元素的position情况。
ff3.5 ie6以上 safari opera chrome都支持getBoundingClientRect方法,如果对兼容性要求不是很高可以用下面的代码
var getOffsetPosition=function(elem){
if ( !elem ) return {left:0, top:0};
var top = 0, left = 0;
if ( "getBoundingClientRect" in document.documentElement ){
//jquery方法
var box = elem.getBoundingClientRect(),
doc = elem.ownerDocument,
body = doc.body,
docElem = doc.documentElement,
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
top = box.top + (self.pageYOffset || docElem && docElem.scrollTop || body.scrollTop ) - clientTop,
left = box.left + (self.pageXOffset || docElem && docElem.scrollLeft || body.scrollLeft) - clientLeft;
}else{
do{
top += elem.offsetTop || 0;
left += elem.offsetLeft || 0;
elem = elem.offsetParent;
} while (elem);
}
return {left:left, top:top};
}
计算时需要减去clientTop clientLeft,否则有时还是会差几个像素。