獲取元素距離瀏覽器周邊的位置的方法getBoundingClientRect
更新時間:2013年04月17日 11:40:15 作者:
本文為大家介紹下如何使用getBoundingClientRect()方法獲取元素距離瀏覽器周邊的位置,有類似問題的朋友可以參考下哈,希望對你學習js有所幫助
復制代碼 代碼如下:
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 )
您可能感興趣的文章:

