关于javascript的getBoundingClientRect() API

关于mdn的描述

返回值是一个 DOMRect 对象,是包含整个元素的最小矩形(包括 padding 和 border-width)。该对象使用 lefttoprightbottomxywidth 和 height 这几个以像素为单位的只读属性描述整个矩形的位置和大小。除了 width 和 height 以外的属性是相对于视图窗口的左上角来计算的。

如:bottom 是盒子底部边框 距离 视口顶部 的距离;right 是盒子右侧边框距离视口左侧的距离。

位置相关属性如下:

代码详解:

<style>
  * {
    margin: 0;
    padding: 0;
  }
  .box {
    width: 400px;
    height: 200px;
    margin: 100px auto;
    border: 1px solid #ccc;
  }
  .child {
    width: 200px;
    height: 100px;
    margin: 20px;
    border: 1px solid #ccc;
  }
</style>
<body>
  <div class="box">
    <div class="child">
      child
    </div>
  </div>
</body>
<script>
  const childDom = document.querySelector('.child');
  console.log(childDom.getBoundingClientRect());
  // top: 100     --- 盒子上边框距离视口顶部的距离
  // bottom: 302  --- 盒子底边框距离视口顶部的距离 = top + height
  // left: 394    --- 盒子左边框距离视口左侧的距离
  // right: 796   --- 盒子右边框距离视口左侧的距离 = left + width
  // x: 394       --- 盒子左上角相对于视口左侧的距离
  // y: 100       --- 盒子左上角相对于视口顶部的距离

  // 盒子的宽高
  // width: 402
  // height: 202
</script>

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值