【问题标题】:How to programmatically tell if two absolutely positioned elements overlap?如何以编程方式判断两个绝对定位的元素是否重叠?
【发布时间】:2020-09-30 10:52:04
【问题描述】:

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

^这是最简单的方法吗?

【问题讨论】:

  • 您只关心未转换的矩形元素,即只关心它们的边界框?那么是的,您的算法应该没问题,您可以使用 developer.mozilla.org/en-US/docs/Web/API/Element/… 获得 A 和 B 如果您需要考虑旋转或剪辑元素,那就是另一回事了。

标签: javascript html dom css-position overlapping


【解决方案1】:

这本质上是和 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

【讨论】:

    【解决方案2】:

    只是对你所拥有的东西进行了轻微的改变。

    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>

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2015-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多