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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月23日
2024年09月23日
- 国风大师纯音系列《古筝仙子 常静演奏 十指弹一》1CD[FLAC][919MB]
- DasKapital-OneMustHaveChaosInsidetoGiveBirthtoaDancingStar(2024)[24-44.1]WAV
- 王菲.1999-《只爱陌生人》日本东芝版[低速原抓WAV+CUE]
- 张小英1987-金奖金曲第一集[新加坡版][WAV+CUE]
- 鹿晗.2015-重启【海蝶】【FLAC分轨】
- 张芸京.2012-小女孩【金牌大风】【WAV+CUE】
- 余天.2002-雄狮魅力金曲2CD(南方金点系列)【南方】【WAV+CUE】
- 银霞.1982-《结·SAYYESMYBOY》台湾复刻版[WAV+CUE]
- 梁汉文1993-火热动感[引进版][WAV+CUE]
- 梁汉文2008-EDMONDHITS48[香港]3CD[WAV+CUE]
- 国风大师纯音系列《童丽-[渭城曲]》1CD[WAV分轨][593.5MB]
- 国风大师纯音系列《许菱子《烧筝2》古筝曲集》1CD[WAV分轨][1.3GB]
- 王子异《1996 Part.2》[320K/MP3][18.29MB]
- 群星.1994-宝丽金最倾情3CD【宝丽金】【WAV+CUE】
- 乐俊亨.2024-同泪【CharioticMusic】【FLAC分轨】