// 获取元素的坐标位置,可以使用 getBoundingClientRect() 方法。
// 该方法返回一个 DOMRect 对象,提供元素的大小及其相对于视口的位置。
function getElementPosition(element) {
const rect = element.getBoundingClientRect();
const position = {
top: rect.top + window.scrollY,
left: rect.left + window.scrollX,
bottom: rect.bottom + window.scrollY,
right: rect.right + window.scrollX,
width: rect.width,
height: rect.height
};
return position;
}
// 示例用法:
const myElement = document.getElementById('myElementId');
const position = getElementPosition(myElement);
console.log(position); // 输出元素的坐标信息
// 解释:
// - getBoundingClientRect() 返回的坐标是相对于视口(viewport)的。
// - 为了获取相对于整个文档的坐标,需要加上当前页面的滚动偏移量(window.scrollY 和 window.scrollX)。
// - 返回的对象包含 top, left, bottom, right, width, height 等属性,分别表示元素的上、左、下、右边缘以及宽度和高度。
上一篇:js 获取元素位置
下一篇:js 获取焦点
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站