JavaScript 获取div的坐标位置、宽度、高度 getBoundingClientRect() 作者:马育民 • 2024-10-17 20:05 • 阅读:10004 # 说明 可用下面方法获取 div 的坐标、宽度、高度 ``` 元素.getBoundingClientRect() ``` [![](/upload/0/0/1IX8ckoP71bF.png)](/upload/0/0/1IX8ckoP71bF.png) **返回值:** 是一个 `DOMRect` 对象,是包含整个元素的最小矩形(包括 padding 和 border-width)。该对象有以下属性: - left:参加上图 - top:参加上图 - right:参加上图 - bottom:参加上图 - x:参加上图 - y:参加上图 - width:元素的宽度,包含:padding 和 border - height:元素的高度,包含:padding 和 border ### 例子 ``` const square = document.getElementsByName("square") const rect = square.getBoundingClientRect() console.log(rect) ``` 执行结果: ``` bottom: 178.79999923706055 height: 120 left: 183.8000030517578 right: 188.8000030517578 top: 58.79999923706055 width: 5 x: 183.8000030517578 y: 58.79999923706055 ``` 参考: https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect https://blog.csdn.net/weixin_61597234/article/details/134878221 原文出处:http://malaoshi.top/show_1IX8ckrfPBWO.html