JS获取点击元素坐标方法 Element.getBoundingClientRect();

339 阅读1分钟

question:如何获取点击元素的坐标呢?

answer: 原生标签元素的方法 Element.getBoundingClientRect();

<div onclick="clickElement()">
<div>
// 触发元素的点击事件
function clickElement(e) {
    // 元素的 getBoundingClientRect()能够获取到点击元素相对于 “浏览器视口” 所在的坐标
    const rect = e.target.getBoundingClientRect();
    // rect 是一个包含标签元素位置信息相关的对象
    console.log(rect ); 
/* rect对象如下
{
  x : 146 // 元素左上角距离浏览器视图左上角的横坐标的值
  y : 50   // 元素左上角距离浏览器视图左上角的纵坐标的值
  width : 440 
  height : 240
  top : 50
  right : 586
  bottom : 290
  left : 146
}*/
}

对象的相关属性如下图所示

image.png