利用 getBoundingClientRect 计算两个dom的相差距离

利用 getBoundingClientRect 计算两个dom的相差距离


getBoundingClientRect-MDN

  • getBoundingClientRect原点 不受其他因素影响,始终为浏览器左上角
  • 当两个 dom 的判断原点相同时,不需要考虑其他因素,拿dom1的尾部 去 减去 dom2 的头部,就是想要的 距离
  • 此时的相减,正常来说,dom2 是在 dom1 下方,则必然是负数,可以在这里绝对值一下,我利用-号获取到我想要的正数,如果此时的返回值还是负数,则表明 dom2 在 dom1上方了
  • 获取距离,取返回对象中的 bottomAndTop
/**
 * @name: 计算2个元素的距离
 */
export const getDistance = (dom1, dom2) => {
  // getBoundingClientRect() 方法返回元素的大小及其相对于视窗的位置,元素的margin不被视为元素内容,所以放回的距离始终是padding的距离
  const rect1 = dom1.getBoundingClientRect()
  const rect2 = dom2.getBoundingClientRect()
  const x = rect1.left - rect2.left
  const y = rect1.bottom - rect2.top

  return {
    topAndTop: -(rect1.top - rect2.top),
    // 两个元素相差的距离,负数表示 dom1在dom2的下方,正数表示 dom1在dom2的上方,所以取反
    bottomAndTop: -(rect1.bottom - rect2.top),
    topAndBottom: -(rect1.top - rect2.bottom),
    bottomAndBottom: -(rect1.bottom - rect2.bottom),
    cross: Math.sqrt(x * x + y * y),
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值