当前位置:Gxlcms > JavaScript > 获取元素距离浏览器周边的位置的方法getBoundingClientRect

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

时间:2021-07-01 10:21:17 帮助过:5人阅读

代码如下:

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 )

人气教程排行