一.getBoundingClientRect()
功能:用于获得页面中某个元素的左、上、右和下分别相对浏览器视窗的位置,以及元素宽高和元素左上角所在浏览器得x、y得坐标。
参数:无需传参
注意:getBoundingClientRect()是DOM元素到浏览器可视范围的距离(不包含文档卷起的部分)。
该函数返回一个Object对象,该对象有8个属性:x,y,top,lef,right,bottom,width,height;
html:
<div id="box"></div>
js:
var object = document.getElementById('box').getBoundingClientRect();
console.log(JSON.stringify(object))
可以看到打印的结果:
{"x":8,"y":8,"width":200,"height":200,"top":8,"right":208,"bottom":208,"left":8}
x: 元素左上角距离视窗左边的距离
y: 元素左上角距离视窗上左边的距离
width: 元素自身的宽
height: 元素自身的高
top: 元素上边到视窗上边的距离;
right: 元素右边到视窗左边的距离;
bottom: 元素下边到视窗上边的距离;
left: 元素左边到视窗左边的距离;
二.兼容性
用ie11的Document Mode模式测试,ie5以上都能支持。
1.width和height:ie9以上支持width/height属性。
兼容ie6~ie8的width/height的写法:
var rectWidth = rectObject.right - rectObject.left;
rectHeight = rectObject.bottom - rectObject.top;
2.在ie7及ie7以下left和top会多出两个像素。
ie7下测试:
chrome下测试:
document.documentElement在ie7及ie7以下会多出两个像素。
在ie7及ie7以下的html元素坐标会从(2, 2)开始算起,在ie8已经修复了这个bug。这就是多出两个像素的原因。
做下兼容:
var rectLeft = rectobject.left - document.documentElement.clientLeft || 2;
var rectRight = rectobject.right - document.documentElement.clientLeft || 2;
var rectBottom = rectobject.bottom - document.documentElement.clientTop || 2;
var rectTop = rectobject.top - document.documentElement.clientTop || 2;