getBoundingClientRect()

来源:互联网 发布:ps淘宝美工 编辑:程序博客网 时间:2024/06/03 21:03

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    }}