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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:06:08