Intersection Observer:它可以用来检测容器中两个元素之间的碰撞吗?

dar*_*ong 7 javascript intersection-observer

在下面的示例代码中,isIntersecting总是true,可能是因为相交的主题是父对象本身。

有没有办法使用 IntersectionObserver 来检测两个盒子之间的相交/碰撞?

我们的想法是使用这个内置 API,因为每当任何框位置发生更改时都需要检查交叉点;在原始代码中,它们从一个位置转换到另一个位置,并在检测到碰撞时立即做出反应。例如,这将是轮询的一个有趣的替代方案。

任何想法都会很棒。

/** @type {HTMLDivElement[]} */
    const elements = Array.from(document.getElementsByClassName('box'));

    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          console.log(
            `${entry.target.className} is overlapping with another element`
          );
        }
      });
    });
    
    console.log('elements', elements);

    elements.forEach((div) => observer.observe(div));
Run Code Online (Sandbox Code Playgroud)
#container {
  width: 150px;
  height: 150px;
  position: relative;
  background-color: aqua;
}

.box {
  width: 32px;
  height: 32px;
  border: 1px solid #333;
  background-color: yellow;
  position: absolute;
}
Run Code Online (Sandbox Code Playgroud)
<div id="container">
  <div class="box" style="left: 8px; top: 8px;"></div>
  <div class="box" style="left: 48px; top: 48px;"></div>
</div>
Run Code Online (Sandbox Code Playgroud)