当前位置: 首页 > news >正文

JavaScript获取鼠标点一个元素,获取鼠标点击的元素内的位置

JavaScript获取鼠标点一个元素,获取鼠标点击的元素内的位置

//event事件
function getEventPosition(event) {// 使用 getBoundingClientRect() 获取更精确的位置const rect = canvas.getBoundingClientRect();const x = event.clientX - rect.left;const y = event.clientY - rect.top;return { x: x, y: y };
}

getBoundingClientRect() 是一个用于获取元素位置和尺寸信息的重要方法2。

‌核心功能‌
它返回一个DOMRect对象,包含以下关键属性23:

    • x / left:元素左边界相对于视口左侧的距离
    • y / top:元素上边界相对于视口顶部的距离
    • width:元素的宽度
    • height:元素的高度
    • right:元素右边界相对于视口左侧的距离
    • bottom:元素下边界相对于视口顶部的距离
    • const box = document.getElementById('box');
      const rect = box.getBoundingClientRect();console.log(rect.width);   // 元素的宽度
      console.log(rect.height); // 元素的高度
      console.log(rect.top);    // 元素上边界相对于视口顶部的距离