PHP前端开发

js如何查坐标

百变鹏仔 4天前 #JavaScript
文章标签 坐标
使用 getboundingclientrect() 方法获取元素相对文档视口的坐标,包括:左上角 x 坐标 (left)左上角 y 坐标 (top)元素宽度 (width)元素高度 (height)

如何在 JavaScript 中查坐标

快速解答:

可以使用 getBoundingClientRect() 方法获取元素相对于文档视口的坐标。

详细解释:

1. 获取元素的边框框 (Bounding Box)

getBoundingClientRect() 方法返回一个对象,该对象包含元素边框框的坐标。边框框是一个矩形,其四个角的坐标分别为:

2. 使用坐标

获取边框框坐标后,就可以在以下场景中使用它们:

3. 示例代码

以下代码演示如何使用 getBoundingClientRect() 获取元素的坐标:

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); // 元素的高度