Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 获取元素坐标

作者:傲世,小狂徒   发布日期:2025-04-09   浏览:26

// 获取元素的坐标位置,可以使用 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 获取焦点

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 获取今天年月日

js jsonp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站