首頁 > web前端 > js教程 > 主體

在js中getBoundingClientRect有什麼作用?

亚连
發布: 2018-06-08 14:49:49
原創
1945 人瀏覽過

這篇文章主要介紹了js中getBoundingClientRect的作用及相容方案詳解,現在分享給大家,也給大家做個參考。

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元素相對於視窗的位置集合的方法

<p id="test" style="width: 100px; height: 100px; background: #ddd;"></p>
<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(&#39;test&#39;));
 alert("top:" + test.top + ", right:" + test.right + ", bottom:" + test.bottom + ", left:" + test.left);
</script>
登入後複製

上面是我整理給大家的,希望今後會對大家有幫助。

相關文章:

JS中Number類型(詳細教學)

在Angular如何使用瀏覽器外掛程式Batarang

#在vue中預先載入watch用法

以上是在js中getBoundingClientRect有什麼作用?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!