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); // 元素上边界相对于视口顶部的距离
浙公网安备 33010602011771号