亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

js中g(shù)etBoundingClientRect的作用及兼容方案詳解

 更新時(shí)間:2018年02月01日 14:50:52   作者:limeiky  
這篇文章主要介紹了js中g(shù)etBoundingClientRect的作用及兼容方案詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

1、getBoundingClientRect的作用

getBoundingClientRect用于獲取某個(gè)html元素相對(duì)于視窗的位置集合。

執(zhí)行 object.getBoundingClientRect();會(huì)得到元素的top、right、bottom、left、width、height屬性,這些屬性以一個(gè)對(duì)象的方式返回。

getBoundingClientRect()

這個(gè)方法返回一個(gè)矩形對(duì)象,包含四個(gè)屬性:left、top、right和bottom。分別表示元素各邊與頁(yè)面上邊和左邊的距離。

var box=document.getElementById('box'); // 獲取元素

alert(box.getBoundingClientRect().top); // 元素上邊距離頁(yè)面上邊的距離

alert(box.getBoundingClientRect().right); // 元素右邊距離頁(yè)面左邊的距離

alert(box.getBoundingClientRect().bottom); // 元素下邊距離頁(yè)面上邊的距離

alert(box.getBoundingClientRect().left); // 元素左邊距離頁(yè)面左邊的距離

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

主要是left和bottom要解釋一下,left是指右邊到頁(yè)面最左邊的距離,bottom是指底邊到頁(yè)面頂邊的距離。

看圖:

 

3. 瀏覽器兼容性

ie5以上都能支持,但是又一點(diǎn)點(diǎn)地方需要修正一下,

IE67的left、top會(huì)少2px,并且沒(méi)有width、height屬性。

4、利用getBoundingClientRect來(lái)寫(xiě)一個(gè)獲取html元素相對(duì)于視窗的位置集合的方法

<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,其他高級(jí)點(diǎn)的瀏覽器為0
   bottom = xy.bottom,
   left = xy.left-document.documentElement.clientLeft+document.documentElement.scrollLeft,//document.documentElement.clientLeft 在IE67中始終為2,其他高級(jí)點(diǎn)的瀏覽器為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>

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論