getBoundingClientRect获取DOM元素获取的宽和高以及位置

dom.getBoundingClientRect()

记得小程序也有个类似的方法

属性说明:
width, height: 元素的实际宽度 / 宽度
left: 元素左边距离视口左边的距离
right: 元素右边距离视口左边的距离
top: 元素上边距离视口上边的距离
bottom: 元素下边距离视口上边的距离

注意:
宽高包含padding, border
距离根据视口/文档?为起点, 而不是父元素

x, y: 元素左上角距离视口左上角边的距离

代码

.par {
  position: relative;
  top: 0;
  left: 10px
  width: 500px;
  height: 500px;
  background-color: #fff;
}
.back-top {
  position: absolute;
  /* bottom: 50px; */
  left: 10px;
  top: 10px;
  width: 150px;
  height: 150px;
  /* height: 174px; */
  background-color: aqua;
  border: 50px solid #cccccc;
  margin: 10px;
  padding: 20px;
}
<div class="par">
  <div class="back-top" style="right: 0px;display: block;"></div>
</div>
const back = document.querySelector('.back-top')
const distance = back.getBoundingClientRect()
console.log(distance)
// 实际宽为height和width
// 或者实际宽度(290) = right(320) - left(30) //高度同理

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值