getBoundingClientRect使用方法及兼容性处理

php中世界最好的语言
php中世界最好的语言 原创
2018-04-13 09:35:56 4231浏览

这次给大家带来getBoundingClientRect使用方法及兼容性处理,getBoundingClientRect使用方法及兼容性处理的注意事项有哪些,下面就是实战案例,一起来看一下。

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); // 元素左边距离页面左边的距离

浏览器兼容性

ie5以上都能支持,但是又一点点地方需要修正一下,

IE67的left、top会少2px,并且没有width、height属性。

利用getBoundingClientRect来写一个获取html元素相对于视窗的位置集合的方法

<p id="test" style="width: 100px; height: 100px; background: #ddd;"></p>
<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>

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

vue实现购物车的小球抛物线效果详解

Vue.js中组件使用详解

以上就是getBoundingClientRect使用方法及兼容性处理的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。