Element.getBoundingClientRect() 方法返回一个 DOMRect 对象,其提供了元素的大小及其相对于视口的位置。
语法
getBoundingClientRect()
返回值
返回值是一个 DOMRect 对象,是包含整个元素的最小矩形(包括 padding 和 border-width)。该对象使用 left、top、right、bottom、x、y、width 和 height 这几个以像素为单位的只读属性描述整个矩形的位置和大小。除了 width 和 height 以外的属性是相对于视图窗口的左上角来计算的。
示例
控制台输出
代码
<style>
div {
position: absolute;
left: 50%;
top: 25%;
width: 200px;
height: 200px;
transform: translateX(-50%);
background-color: pink;
}
</style>
<body>
<div></div>
<script>
const div = document.querySelector('div')
console.log(div.getBoundingClientRect());
</script>
</body>