You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中生成不重叠的元素随机位置?

实现不重叠的随机元素位置

需求是生成两个不重叠的随机位置元素,既定思路:

  • 生成随机位置
  • 检查位置是否重叠
  • 重叠则重新生成位置

原代码仅随机生成元素位置,未做重叠校验,因此两个元素大概率会出现重叠情况。以下是优化后的完整实现:

HTML 代码

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">
    <title>random position</title>
  </head>
  <body>
    <script src="script.js" type="text/javascript"></script>
  </body>
</html>

CSS 代码

.div01 {
    position: absolute;
    background-color: red;
    width: 50px;
    height: 50px;
}

.div02 {
    position: absolute;
    background-color: blue;
    width: 50px;
    height: 50px;
}

JavaScript 代码

// 生成随机位置,范围调整为避免元素超出可视区域
function randomPosition(size) {
    // 最小位置0,最大位置为窗口尺寸减去元素自身尺寸
    return parseInt(Math.random() * (window.innerWidth - size));
}

// 检查两个元素是否重叠
function checkOverlap(el1, el2) {
    const rect1 = el1.getBoundingClientRect();
    const rect2 = el2.getBoundingClientRect();
    // 反向判断:如果元素在对方的左、右、上、下侧,则不重叠,否则重叠
    return !(rect1.right < rect2.left || 
             rect1.left > rect2.right || 
             rect1.bottom < rect2.top || 
             rect1.top > rect2.bottom);
}

// 创建元素
let div01 = document.createElement('div');
div01.setAttribute('class', 'div01');

let div02 = document.createElement('div');
div02.setAttribute('class', 'div02');

document.body.append(div01, div02);

// 设置第一个元素的位置
const elSize = 50; // 元素宽高
div01.style.top = randomPosition(elSize) + 'px';
div01.style.left = randomPosition(elSize) + 'px';

// 生成第二个元素的位置,直到不重叠
do {
    div02.style.top = randomPosition(elSize) + 'px';
    div02.style.left = randomPosition(elSize) + 'px';
} while (checkOverlap(div01, div02));

关键逻辑说明

  • 随机位置优化:调整randomPosition函数的范围,确保元素不会超出浏览器可视区域,避免出现元素部分或完全不可见的情况。
  • 重叠检测:checkOverlap函数通过getBoundingClientRect()获取元素的位置和尺寸信息,利用矩形边界的关系判断是否重叠,逻辑简洁高效。
  • 循环生成位置:使用do-while循环,确保第二个元素生成的位置一定与第一个元素不重叠后才停止循环。

内容的提问来源于stack exchange,提问作者Jean

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 08:10:28