利用 getBoundingClientRect 计算两个dom的相差距离
getBoundingClientRect-MDN
- getBoundingClientRect 的 原点 不受其他因素影响,始终为浏览器左上角
- 当两个 dom 的判断原点相同时,不需要考虑其他因素,拿dom1的尾部 去 减去 dom2 的头部,就是想要的 距离
- 此时的相减,正常来说,dom2 是在 dom1 下方,则必然是负数,可以在这里绝对值一下,我利用-号获取到我想要的正数,如果此时的返回值还是负数,则表明 dom2 在 dom1上方了
- 获取距离,取返回对象中的 bottomAndTop
export const getDistance = (dom1, dom2) => {
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),
bottomAndTop: -(rect1.bottom - rect2.top),
topAndBottom: -(rect1.top - rect2.bottom),
bottomAndBottom: -(rect1.bottom - rect2.bottom),
cross: Math.sqrt(x * x + y * y),
}
}