js中g(shù)etBoundingClientRect的作用及兼容方案詳解
1、getBoundingClientRect的作用
getBoundingClientRect用于獲取某個html元素相對于視窗的位置集合。
執(zhí)行 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>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Cropper.js進階之固定寬高圖片裁切實現(xiàn)示例
這篇文章主要為大家介紹了Cropper.js進階之固定寬高圖片裁切實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05
easyui給某一個單元格的內(nèi)容增加下劃線的操作方法
在EasyUI的DataGrid組件中,你可以通過自定義單元格的渲染方式來實現(xiàn)給某一個單元格的內(nèi)容增加下劃線的效果,本文給大家介紹easyui如何給某一個單元格的內(nèi)容增加下劃線,感興趣的朋友跟隨小編一起看看吧2024-08-08
js定義對象或數(shù)組直接量時各瀏覽器對多余逗號的處理(json)
定義對象或數(shù)組直接量時不同瀏覽器引擎對多余逗號的處理,js報錯分為兩種:語法錯誤和運行錯誤。2011-03-03
學(xué)習(xí)Javascript閉包(Closure)知識
這篇文章主要介紹了學(xué)習(xí)Javascript閉包(Closure)知識的相關(guān)資料,需要的朋友可以參考下2016-08-08

