js中getBoundingClientRect的作用及兼容方案详解
网络编程 2021-07-04 17:33www.168986.cn编程入门
这篇文章主要介绍了js中getBoundingClientRect的作用及兼容方案详解,长沙网络推广觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随长沙网络推广过来看看吧
1、getBoundingClientRect的作用
getBoundingClientRect用于获取某个html元素相对于视窗的位置集合。
执行 object.getBoundingClientRect();会得到元素的、right、bottom、left、width、height属性,这些属性以一个对象的方式返回。
getBoundingClientRect()
这个方法返回一个矩形对象,包含四个属性:left、、right和bottom。分别表示元素各边与页面上边和左边的距离。
var box=document.getElementById('box'); // 获取元素 alert(box.getBoundingClientRect().); // 元素上边距离页面上边的距离 alert(box.getBoundingClientRect().right); // 元素右边距离页面左边的距离 alert(box.getBoundingClientRect().bottom); // 元素下边距离页面上边的距离 alert(box.getBoundingClientRect().left); // 元素左边距离页面左边的距离
2.getBoundingClientRect上下左右属性值解释
主要是left和bottom要解释一下,left是指右边到页面最左边的距离,bottom是指底边到页面顶边的距离。
看图:
3. 浏览器兼容性
ie5以上都能支持,但是又一点点地方需要修正一下,
IE67的left、会少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 = xy.-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 - ; return { :, right:right, bottom:bottom, left:left, width:width, height:height } } var test = getObjXy(document.getElementById('test')); alert(":" + test. + ", right:" + test.right + ", bottom:" + test.bottom + ", left:" + test.left); </script>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持狼蚁SEO。
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程