JavaScript:如何检测DOM元素与其他DOM元素重叠、内部或外部?

5
我正在使用JavaScript制作一个小游戏。我创建了一个小的示例js fiddle demo link。下面列出了三种情况:
  • A:在目标对象外部。
  • B:与目标对象的边框重叠。
  • C:在目标对象内部。
根据Have object detect if completely inside other object JavaScript,我知道如何检测对象是否在目标对象内部(情况C)。那么A和B情况呢?
<div class="main">
    <div class="target"></div>
    <div class="obj">A</div>
    <div style="top:15%; left:50%;" class="obj">B</div>
    <div style="top:25%; left:35%;" class="obj">C</div>
</div>
1个回答

3

一种方法是使用Element#getBoundingClientRect()获取被归类元素的绝对坐标,以判断是否重叠或包含等。

该函数将返回相应DOM元素的toprightbottomleft坐标,您可以使用这些坐标确定element相对于container的包含关系。

您可以实现如下的findContainment()函数来比较elementcontainer之间的包含关系:

function findContainment(element, container) {

  /*
  Obtain the bounding rectangle for each element 
  */
  const brE = element.getBoundingClientRect()
  const brC = container.getBoundingClientRect()

  /* 
  If the boundaries of container pass through the boundaries of
  element then classifiy this as an overlap 
  */
  if (
    /* Does container left or right edge pass through element? */
    (brE.left < brC.left && brE.right > brC.left) ||
    (brE.left < brC.right && brE.right > brC.right) ||
    /* Does container top or bottom edge pass through element? */
    (brE.top < brC.top && brE.bottom > brC.top) ||
    (brE.top < brC.bottom && brE.bottom > brC.bottom)) {

    return "overlap";
  }

  /* 
  If boundaries of element fully contained inside bounday of
  container, classify this as containment of element in container
  */
  if (
    brE.left >= brC.left &&
    brE.top >= brC.top &&
    brE.bottom <= brC.bottom &&
    brE.right <= brC.right
  ) {
    return "contained"
  }

  /* 
  Otherwise, the element is fully outside the container 
  */
  return "outside"

}

const main = document.querySelector(".main")
console.log("A", findContainment(document.querySelector(".a"), main))
console.log("B", findContainment(document.querySelector(".b"), main))
console.log("C", findContainment(document.querySelector(".c"), main))
console.log("D", findContainment(document.querySelector(".d"), main))
console.log("E", findContainment(document.querySelector(".e"), main))
.main {
  width: 50%;
  height: 200px;
  border: 5px solid #000;
  position: relative;
}

.obj {
  width: 40px;
  height: 40px;
  border: 1px solid blue;
  position: absolute;
}
<div class="main">
  <div style="top:105%; left:25%;" class="obj a">A</div>
  <div style="top:15%; left:-5%;" class="obj b">B</div>
  <div style="top:20%; left:40%;" class="obj c">C</div>
  <div style="top:20%; left:110%;" class="obj d">D</div>
  <div style="top:90%; left:95%;" class="obj e">E</div>
</div>

这里也有一个演示代码,希望能够帮到你!


您提供的小提琴链接与我的相同。能否请您更新一下呢? - peggy
@peggy 对不起,刚刚更新了 - 这样有帮助吗? - Dacre Denny
是的,这正是我想要的。谢谢。 - peggy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接