关于mdn的描述
返回值是一个 DOMRect 对象,是包含整个元素的最小矩形(包括
padding
和border-width
)。该对象使用left
、top
、right
、bottom
、x
、y
、width
和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>