JS开发RGB猜色游戏时无法给div设置预定义获胜颜色如何解决
问题修复点
- 循环条件错误:你写的
i<=box.length会导致数组越界,box有3个元素,索引范围是0-2,应该改为i<box.length - 随机颜色生成逻辑错误:
var r,g,b = Math.floor(Math.random() * 256)仅给b赋值,r和g都是undefined,需要分别给三个通道赋值 - 点击事件参数错误:监听回调的参数是事件对象,需要通过
el.target获取被点击的div元素,不能直接用el.style - DOM获取错误:
getElementsByTagName返回的是HTML集合,需要取下标[0]才能拿到对应的h1元素 - 重复绑定事件问题:每次调用
gamestart都会给div绑定新的点击事件,会导致多次触发逻辑,建议只绑定一次事件
修复后完整JS代码
// 提前获取DOM元素,避免重复查询 const boxes = document.querySelectorAll('.box'); const colorGuessEl = document.getElementById('colorguess'); const titleEl = document.querySelector('h1'); let rgbValueTrue = ''; // 仅绑定一次点击事件 boxes.forEach(box => { box.addEventListener('click', function(e) { if (e.target.style.backgroundColor === rgbValueTrue) { titleEl.textContent = "BRAVO"; // 猜对后1.5秒重置游戏,不需要可以删除这行 setTimeout(gamestart, 1500); } else { gamestart(); } }) }) function gamestart() { // 重置标题 titleEl.textContent = "Guess The Color!"; // 生成正确颜色 const r = Math.floor(Math.random() * 256); const g = Math.floor(Math.random() * 256); const b = Math.floor(Math.random() * 256); rgbValueTrue = `rgb(${r}, ${g}, ${b})`; colorGuessEl.textContent = rgbValueTrue; // 给所有盒子生成随机颜色 boxes.forEach(box => { const rndR = Math.floor(Math.random() * 256); const rndG = Math.floor(Math.random() * 256); const rndB = Math.floor(Math.random() * 256); box.style.backgroundColor = `rgb(${rndR}, ${rndG}, ${rndB})`; }) // 随机选一个盒子设为正确颜色 const randomIndex = Math.floor(Math.random() * 3); boxes[randomIndex].style.backgroundColor = rgbValueTrue; } gamestart();
内容的提问来源于stack exchange,提问作者Anđelo Motika
相关产品推荐
相关产品推荐

