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

时间:2020-09-26 04:50:33

标签: javascript html dom css-position overlapping

我认为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
}

^这是最简单的方法吗?

3 个答案:

答案 0 :(得分:0)

这本质上是和x,y比较的问题。本质上,如果它们在任意位置重叠,则需要在所有边界(顶部,右侧,底部和左侧)的x,y位置比较两个元素。

一种简单的方法是测试它们是否重叠。

如果以下任何一项都不成立,则可以认为两个项目重叠:

 - 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

答案 1 :(得分:0)

对您所拥有的内容仅稍作更改。

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>

答案 2 :(得分:0)

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

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))
  );
};
相关问题