温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScript中getBoundingClientRect的作用是什么

发布时间:2021-06-25 15:15:11 来源:亿速云 阅读:205 作者:Leah 栏目:web开发

本篇文章给大家分享的是有关JavaScript中getBoundingClientRect的作用是什么,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

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是指底边到页面顶边的距离。

看图:

 JavaScript中getBoundingClientRect的作用是什么

3. 浏览器兼容性

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

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

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

<div id="test" ></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>

以上就是JavaScript中getBoundingClientRect的作用是什么,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI