获取元素距离浏览器周边的位置的方法getBoundingClientRect
匿名 · 更新于 2014/3/23
<input type="text" id="inp" />
<script type="text/javascript">
var box = document.getElementById( "inp" );
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 // 距离右边的位置就是 距离左边的位置加上元素本身的宽度
};
};
</script>
