国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

js中getBoundingClientRect的作用及兼容方案詳解

2019-11-19 14:25:59
字體:
來源:轉載
供稿:網友

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>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 驻马店市| 彭水| 康平县| 阳朔县| 家居| 沧州市| 铁岭市| 株洲县| 武胜县| 桐梓县| 明溪县| 泰和县| 江川县| 黄冈市| 恭城| 鄱阳县| 项城市| 柳林县| 柯坪县| 治县。| 永年县| 永福县| 宁乡县| 湘阴县| 益阳市| 新化县| 泰和县| 古丈县| 兰西县| 读书| 秦皇岛市| 育儿| 临洮县| 嘉鱼县| 家居| 鄂伦春自治旗| 阜新| 怀远县| 郴州市| 怀远县| 凉城县|