如何以编程方式判断两个绝对定位的元素是否重叠?

How to programmatically tell if two absolutely positioned elements overlap?

我觉得DOMAPI里面没有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
}

^这是最简单的方法吗?

这本质上是和x,y比较的问题。如果它们在任何地方重叠,您基本上需要通过所有边界(顶部、右侧、底部和左侧)的 x、y 位置来比较这两个元素。

一个简单的方法是,测试它们是否不重叠。

如果满足以下 none 项,则可以认为两个项目重叠:

 - box1.right < box2.left // too far left
 - box1.left > box2.right // too far right
 - box1.bottom < box2.top // too far above
 - box1.top > box2.bottom // too far below

只是对您所拥有的内容稍作改动。

function checkOverlap(elm1, elm2) {
  e1 = elm1.getBoundingClientRect();
  e2 = elm2.getBoundingClientRect();
  return e1.x <= e2.x && e2.x < e1.x + e1.width &&
         e1.y <= e2.y && e2.y < e1.y + e1.height;
}
window.onload = function() {
  var a = document.getElementById('a');
  var b = document.getElementById('b');
  var c = document.getElementById('c');
  
 console.log("a & b: "+checkOverlap(a,b));
 console.log("a & c: "+checkOverlap(a,c));
 console.log("b & c: "+checkOverlap(b,c));
}
<div id="a" style="width:120px;height:120px;background:rgba(12,21,12,0.5)">a</div>
<div id="b" style="position:relative;top:-30px;width:120px;height:120px;background:rgba(121,211,121,0.5)">b</div>
<div id="c" style="position:relative;top:-240px;left:120px;width:120px;height:120px;background:rgba(211,211,121,0.5)">c</div>

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

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))
  );
};