1、getBoundingClientRect的作用
getBoundingClientRect用于獲取某個html元素相對于視窗的位置集合。
執行 object.getBoundingClientRect();會得到元素的top、right、bottom、left、width、height屬性,這些屬性以一個對象的方式返回。
getBoundingClientRect()
這個方法返回一個矩形對象,包含四個屬性:left、top、right和bottom。分別表示元素各邊與頁面上邊和左邊的距離。
var box=document.getElementById('box'); // 獲取元素alert(box.getBoundingClientRect().top); // 元素上邊距離頁面上邊的距離alert(box.getBoundingClientRect().right); // 元素右邊距離頁面左邊的距離alert(box.getBoundingClientRect().bottom); // 元素下邊距離頁面上邊的距離alert(box.getBoundingClientRect().left); // 元素左邊距離頁面左邊的距離2.getBoundingClientRect上下左右屬性值解釋
主要是left和bottom要解釋一下,left是指右邊到頁面最左邊的距離,bottom是指底邊到頁面頂邊的距離。
看圖:

3. 瀏覽器兼容性
ie5以上都能支持,但是又一點點地方需要修正一下,
IE67的left、top會少2px,并且沒有width、height屬性。
4、利用getBoundingClientRect來寫一個獲取html元素相對于視窗的位置集合的方法
<div id="test" style="width: 100px; height: 100px; background: #ddd;"></div><script> function getObjXy(obj){ var xy = obj.getBoundingClientRect(); var top = xy.top-document.documentElement.clientTop+document.documentElement.scrollTop,//document.documentElement.clientTop 在IE67中始終為2,其他高級點的瀏覽器為0 bottom = xy.bottom, left = xy.left-document.documentElement.clientLeft+document.documentElement.scrollLeft,//document.documentElement.clientLeft 在IE67中始終為2,其他高級點的瀏覽器為0 right = xy.right, width = xy.width||right - left, //IE67不存在width 使用right - left獲得 height = xy.height||bottom - top; return { top:top, right:right, bottom:bottom, left:left, width:width, height:height } } var test = getObjXy(document.getElementById('test')); alert("top:" + test.top + ", right:" + test.right + ", bottom:" + test.bottom + ", left:" + test.left);</script>以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答