JS拿到页面某个元素的坐标范围

需求多出现在需要拖拽的事件中,监听鼠标的坐标和目标坐标范围对比,执行业务逻辑,这个情况比较自由。

1.直接代码实现吧

我的需求是:获取的是拖动table某一行到table中的另一行,确定目标行的数据(这个后面发现onDrop方法里面也能拿到)


const table_dom = document.getElementsByTagName('tbody');// 获得要操作的Table的Dom
const trdom = table_dom[0].getElementsByTagName('tr');// tr元素的Dom,因为不止一行,所以是数组
const dropPoint = e.target.getBoundingClientRect(); // 这里是拿到拖动然后放置后的鼠标坐标点
for (let i = 0; i < trdom?.length; i++) {
    // 这里循环就是找到每一行对于浏览器的坐标,然后根据上下左右进行计算,判断是否在范围内即可;
    const currentDom = trdom[i].getBoundingClientRect();
    if (dropPoint.left >= currentDom.left && dropPoint.right <= currentDom.right &&             
    dropPoint.top >= currentDom.top && dropPoint.bottom <= currentDom.bottom) {
    // 这样我们就找出了tr的某一行,然后执行业务逻辑
    ......
    break;
  }
}

 上述代码是:js原生获取某个元素相对于浏览器来说的坐标范围。

你可能感兴趣的:(javascript,前端)