首页  >  文章  >  web前端  >  获取元素距离浏览器周边的位置的方法getBoundingClientRect_javascript技巧

获取元素距离浏览器周边的位置的方法getBoundingClientRect_javascript技巧

WBOY
WBOY原创
2016-05-16 17:36:471407浏览
复制代码 代码如下:

var box = document.getElementById( "gaga1" );
/* alert( box.getBoundingClientRect().top );
alert( box.getBoundingClientRect().right );
alert( box.getBoundingClientRect().bottom );
alert( box.getBoundingClientRect().left ) */

function getRect( elements ){
var rect = elements.getBoundingClientRect();
var clientTop = document.documentElement.clientTop;
var clientLeft = document.documentElement.clientLeft;
return { // 兼容ie多出的两个px
top : rect.top - clientTop, // 距离顶部的位置
bottom : rect.bottom - clientTop, // 距离顶部加上元素本身的高度就等于bottom的位置
left : rect.left - clientLeft, // 距离左边的位置
right : rect.right - clientLeft // 距离右边的位置就是 距离左边的位置加上元素本身的宽度
};
};
alert( getRect(box).top )
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn