使用 getBoundingClientRect() 方法获取元素相对文档视口的坐标,包括:左上角 x 坐标 (left)左上角 y 坐标 (top)元素宽度 (width)元素高度 (height)

如何在 JavaScript 中查坐标
快速解答:
可以使用 getBoundingClientRect() 方法获取元素相对于文档视口的坐标。
详细解释:
1. 获取元素的边框框 (Bounding Box)
getBoundingClientRect() 方法返回一个对象,该对象包含元素边框框的坐标。边框框是一个矩形,其四个角的坐标分别为:
lefttoprightbottom
2. 使用坐标
获取边框框坐标后,就可以在以下场景中使用它们:
-
确定元素的位置:通过检查
left和top坐标,可以知道元素在页面上的位置。 -
确定元素的尺寸:通过计算
right-left和bottom-top,可以获得元素的宽度和高度。 - 检测元素碰撞:通过比较两个元素的边框框坐标,可以确定它们是否重叠。
3. 示例代码
以下代码演示如何使用 getBoundingClientRect() 获取元素的坐标:
<code class="javascript">const element = document.querySelector('div');
const rect = element.getBoundingClientRect();
console.log(rect.left); // 元素的左上角 x 坐标
console.log(rect.top); // 元素的左上角 y 坐标
console.log(rect.width); // 元素的宽度
console.log(rect.height); // 元素的高度</code>










