如何检查以百分比 JavaScript 重叠的块?

How to check blocks overlapping in in percents JavaScript?

我有两个 div 个不同颜色的方块。我想更改第二个块的颜色,如果它覆盖另一个超过 80%,使用 JavaScript!!!。这是我的代码。结果 - https://i.stack.imgur.com/HDcm4.png

这是我的代码:

.FirstBlock{
    height: 100px;
    width: 100px;
    border: 1px solid black;
    background-color: green;
    opacity: 0.8;
}

.SecondBlock{
    height: 100px;
    width: 100px;
    border: 1px solid black;
    margin-top: -25px;
    background-color: red;
    opacity: 0.8;
}
<body>
    <div class="FirstBlock"></div>
    <div class="SecondBlock"></div>
</body>

您可以使用 getBoundingClientRect.

const boxes = document.querySelectorAll(".box");

function checkOverlap(ele1, ele2) {
  const boundings1 = ele1.getBoundingClientRect();
  const boundings2 = ele2.getBoundingClientRect();

  const top1 = parseInt(boundings1.top);
  const height1 = parseInt(boundings1.height);
  const top2 = parseInt(boundings2.top);

  const overlap = 1 - (top2 - top1) / height1;

  if (overlap >= 0.8) {
    ele2.classList.add("overlap-80");
  }

  // console.log({ ele1, ele2, overlap });
}

checkOverlap(boxes[0], boxes[1]);
checkOverlap(boxes[2], boxes[3]);
checkOverlap(boxes[4], boxes[5]);
body {
  font-family: sans-serif;
}

.box {
  width: 400px;
  height: 100px;
  opacity: 0.5;
}

.box-1, .box-3, .box-5  {
  background: cyan;
}

.box-2 {
  margin-top: -80px;
  background: yellow;
}

.box-4 {
  margin-top: -20px;
  background: yellow;
}

.box-6 {
  margin-top: -90px;
  background: yellow;
}

.overlap-80 {
  border: dashed red 4px;
}
<!DOCTYPE html>
<html>
  <body>
    <div id="app">
      <div>
        <h2>80% Overlap</h2>
        <div class="box box-1"></div>
        <div class="box box-2"></div>
      </div>
      <div>
        <h2>20% Overlap</h2>
        <div class="box box-3"></div>
        <div class="box box-4"></div>
      </div>
        </div>
        <div>
        <h2>90% Overlap</h2>
        <div class="box box-5"></div>
        <div class="box box-6"></div>
      </div>
    </div>
  </body>
</html>

如果方块彼此跟随,您可以使用 transform: translateY 将第二个 div 向上移动其高度的 80%。

如果您要在 div 元素上添加任何内容,我建议使用 rgba 颜色作为背景。我在第二个片段中展示了它的样子。

.FirstBlock,
.SecondBlock
{
  height: 100px;
  width: 100px;
  border: 1px solid black;
  opacity: 0.8;
  background-color: green;
}

.SecondBlock {
  background-color: red;
  transform: translateY(-80%);
}
<body>
  <div class="FirstBlock"></div>
  <div class="SecondBlock"></div>
</body>

如果您不打算在 div 中添加任何内容,您可以通过使用一个 div 和一个伪元素来管理所有这些。

.block,
.block::before {
  position: relative;
  height: 100px;
  width: 100px;
  outline: 1px solid black;
  background-color: green;
}

.block::before {
  content: '';
  background-color: rgba(255, 0, 0, 0.8);
  position: absolute;
  top: 20%;
}
<body>
  <div class="block"></div>
</body>