js中getBoundingClientRect的作用及兼容方案


js中getBoundingClientRect的作用及兼容方案

1、getBoundingClientRect的作用

getBoundingClientRect用於獲取某個html元素相對於視窗的位置集合。
 
執行 object.getBoundingClientRect();會得到元素的top、right、bottom、left、width、height屬性,這些屬性以一個對象的方式返回。
 

2.getBoundingClientRect上下左右屬性值解釋

主要是left和bottom要解釋一下,left是指右邊到頁面最左邊的距離,bottom是指底邊到頁面頂邊的距離。
 
看圖:
js中getBoundingClientRect的作用及兼容方案
 

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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM