迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

使用 JavaScript 检查两个元素是否重叠

作者:迹忆客 最近更新:2022/11/17 浏览次数:

要检查两个元素是否重叠,请使用 getBoundingClientRect() 方法获取一个对象,该对象包含有关元素与视口的相对位置的信息。 然后,比较两个矩形的边界边缘(上、右、下、左)。

以下是本文示例的 HTML。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="box1" style="width: 100px; height: 100px; background-color: salmon; position:absolute;">
      Box 1
    </span>

    <div id="box2" style="width: 100px; height: 100px; background-color: lime">
      Box 2
    </span>

    <div id="box3" style="width: 100px; height:100px; background-color: plum; margin-top: 150px;">
      Box 3
    </div>

    <script src="index.js"></script>
  </body>
</html>

这是相关的 JavaScript 代码。

function elementsOverlap(el1, el2) {
  const domRect1 = el1.getBoundingClientRect();
  const domRect2 = el2.getBoundingClientRect();

  return !(
    domRect1.top > domRect2.bottom ||
    domRect1.right < domRect2.left ||
    domRect1.bottom < domRect2.top ||
    domRect1.left > domRect2.right
  );
}

const el1 = document.getElementById('box1');
const el2 = document.getElementById('box2');
const el3 = document.getElementById('box3');

console.log(elementsOverlap(el1, el2)); // 👉️ true

console.log(elementsOverlap(el1, el3)); // 👉️ false

我们创建了一个可重用的函数来检查两个元素是否重叠并返回一个布尔结果:

  • 如果元素重叠,则为 true。
  • 如果他们不这样做,则为假。

我们使用 getBoundingClientRect() 方法来获取一个对象,该对象包含有关元素与视口的相对位置的信息。

toprightbottomleft 属性描述了元素相对于视口左上角的位置。

请注意 ,当滚动位置发生变化时,矩形的边界边缘(顶部、右侧、底部和左侧)会更改它们的值,因为它们的值是相对于视口的。

如果括号中的所有条件都满足,则元素不重叠并且函数返回 false。

另一方面,如果所有条件都返回 false,则元素重叠。

当我们使用 id 为 box1 和 box2 的元素调用 elementsOverlap 函数时,该函数返回 true,因为第一个元素的位置设置为绝对位置并与第二个元素重叠。

当我们使用第一个和第三个元素调用该函数时,它返回 false,因为第三个元素的 margin-top 为 150px 并且不与第一个重叠。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

JavaScript POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便