首页 > 解决方案 > 如何以编程方式判断两个绝对定位的元素是否重叠?

问题描述

我认为 DOM API 中没有这样的方法element.doesOverlap(otherElement),所以我想我必须手动计算,对吧?不知道有没有捷径。

如果没有,这个方法是什么?似乎有很多方式可以重叠......它会有很多条件。有没有一种简洁的写法?

在伪代码中,我有这个:

if (
  ((A.top < B.bottom && A.top >= B.top)
    || (A.bottom > B.top && A.bottom <= B.bottom))

    &&

    ((A.left < B.right && A.left >= B.left)
    || (A.right > B.left && A.right <= B.right))) {
  // elements A and B do overlap
}

^这是最简单的方法吗?

标签: javascripthtmldomcss-positionoverlapping

解决方案


没有更简单的方法。正确的代码是这样的,涵盖了两个元素重叠的所有可能方式:

const doElementsOverlap = (elementA: any, elementB: any) => {
  const A = elementA.getBoundingClientRect();
  const B = elementB.getBoundingClientRect();
  return (
    ((A.top < B.bottom && A.top >= B.top)
    || (A.bottom > B.top && A.bottom <= B.bottom)
    || (A.bottom >= B.bottom && A.top <= B.top))

    &&

    ((A.left < B.right && A.left >= B.left)
    || (A.right > B.left && A.right <= B.right)
    || (A.left < B.left && A.right > B.right))
  );
};

推荐阅读