如何修复JavaScript记忆游戏中单元格同时高亮的问题?
修复记忆游戏单元格依次高亮的问题
问题原因
当前代码中showLevel函数通过for循环直接调用showCell,所有setTimeout会在循环结束后几乎同时触发,导致所有单元格同时高亮。此外,generateLvl生成的随机数存在索引越界风险(生成的是1到n的数,但单元格索引是0-8)。
修复方案
- 为每个单元格的高亮操作设置递增的延迟时间,让它们按顺序依次触发。
- 修正随机数生成逻辑,确保生成的索引在0-8范围内(对应9个单元格)。
修改后的完整代码
JavaScript
const CELLS = document.getElementsByClassName("cell"); let counter = -1; let level = [[], [], [], []]; function generateLvl(n) { counter++; for (let i = 0; i < n; i++) { // 生成0-8的随机索引,对应9个单元格 level[counter].push(Math.floor(Math.random() * 9)); } } function showCell(index) { CELLS[index].classList.add("active"); setTimeout(() => { CELLS[index].classList.remove("active"); }, 750); } function showLevel() { const INTERVAL = 1000; // 每个高亮动作的间隔(包含高亮时长750ms) level[counter].forEach((cellIndex, index) => { // 每个单元格的延迟时间为索引*间隔,实现依次高亮 setTimeout(() => { showCell(cellIndex); }, index * INTERVAL); }); } generateLvl(3); showLevel();
CSS
.game-box { display: flex; justify-content: center; } .game-table { display: grid; grid-template-columns: 200px 200px 200px; } .cell { width: 200px; height: 200px; border: 1px solid black; transition: background-color 0.2s ease; /* 添加过渡动画让高亮更平滑 */ } .active { background-color: green; }
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./css/style.css"> <title>Memory Game</title> </head> <body> <div class="game-box"> <div class="game-table"> <div class="cell cell-1"></div> <div class="cell cell-2"></div> <div class="cell cell-3"></div> <div class="cell cell-4"></div> <div class="cell cell-5"></div> <div class="cell cell-6"></div> <div class="cell cell-7"></div> <div class="cell cell-8"></div> <div class="cell cell-9"></div> </div> </div> <script src="./js/game.js"></script> </body> </html>
关键说明
- 使用
forEach遍历当前关卡的单元格索引,为每个showCell调用设置index * INTERVAL的延迟,确保每个高亮动作按顺序触发。 - 调整随机数生成逻辑为
Math.floor(Math.random() * 9),避免索引越界导致的错误。 - 给单元格添加过渡动画,让高亮切换更自然。
内容的提问来源于stack exchange,提问作者Gagik Manasyan
相关产品推荐
相关产品推荐

