js中getBoundingClientRect()的用法介绍

平时经常获取一个div的位置,用了定位,取位置还好,在不用定位的情况下,计算一个div在页面的距离,就可以用到getBoundingClientRect()方法。

getBoundingClientRect()  获取元素的位置

用法:

document.documentElement.getBoundingClientRect

var div = document.documentElementById(id);

div .getBoundingClientRect().top         获取div到页面顶端的距离  

div .getBoundingClientRect().bootom        获取div到页面顶端的距离 

div .getBoundingClientRect().left        获取div到页面最左边的距离 

div .getBoundingClientRect().right       获取div到页面最右边的距离

感觉这个属性十分实用,不需要每次都需要去计算!

 

posted @ 2017-04-10 16:41  会飞的Tiger  阅读(866)  评论(0)    收藏  举报