如何使用Javascript在父div内生成多个随机位置的子div?
问题修复方案
核心问题原因
- 父容器
#square未设置position: relative,无法作为子元素绝对定位的位置参照 - 生成的小div未设置
position: absolute,默认块级元素特性导致垂直排列 - 仅手动创建了3个小div,未添加随机位置计算逻辑
onmouseover事件会重复触发确认框,body的onload事件中存在无效引用代码
修改后完整代码
HTML代码
<html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="style.css" rel="stylesheet" type="text/css"> <script src="gamejs.js"></script> <title>Game</title> </head> <body> <h1>Game:</h1> <p>we will create the game over here. no problem just wait and chill and play with us.we will create the game over here. no problem just wait and chill and play with us.</p> <h1>Points: <span id="score">0</span></h1> <br> <div id="square" onmouseover="hoverinside(this)" > <div id="child1"> </div> </div> </body> </html>
CSS代码
h1 { font-weight: bold; color: brown; } #square{ height: 350px; width: 700px; background-color: rgb(170, 168, 168); border: brown solid; position: relative; /* 作为子元素定位参照 */ } /* 小div通用样式,避免重复声明 */ .game-block { width: 55px; height: 55px; position: absolute; cursor: pointer; }
JS代码
let isGameStarted = false; // 防止重复触发游戏 let score = 0; // 积分变量 const colors = ['green', 'yellow', 'red', 'blue', 'purple']; // 小方块颜色池 function hoverinside(x) { if(isGameStarted) return; // 游戏已启动就不再弹确认框 let answer = confirm("Do you want to play the game?"); if (answer == true) { alert("Enjoy the game"); isGameStarted = true; generateBlocks(); } else { alert("If you want to play just hover on the gray area again"); location.reload(); } } function generateBlocks() { const parent = document.getElementById("square"); const parentWidth = parent.offsetWidth; const parentHeight = parent.offsetHeight; const blockSize = 55; // 生成5个小方块 for(let i=0; i<5; i++) { const block = document.createElement('div'); block.className = 'game-block'; block.style.background = colors[Math.floor(Math.random() * colors.length)]; // 计算随机位置,确保不会超出父容器 const randomLeft = Math.floor(Math.random() * (parentWidth - blockSize)); const randomTop = Math.floor(Math.random() * (parentHeight - blockSize)); block.style.left = randomLeft + 'px'; block.style.top = randomTop + 'px'; // 绑定点击删除+积分逻辑 block.addEventListener('click', () => { block.remove(); score++; document.getElementById('score').textContent = score; // 可自行扩展:方块删完后生成新批次/结束游戏逻辑 }) parent.appendChild(block); } }
功能说明
- 修复了随机位置生成逻辑,小方块不会超出灰色父容器范围
- 已内置你后续计划实现的点击删除和积分统计功能,点击小方块即可自动加分
- 增加了游戏启动锁,不会重复弹出确认框
- 删除了原代码中无效的onload引用逻辑
内容的提问来源于stack exchange,提问作者Nayem Shnartho
相关产品推荐
相关产品推荐

