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

浏览器猜图游戏按钮无响应:实现点击弹窗与图片去模糊

猜图游戏问题排查与修复方案

核心问题梳理

  • getElementsByClassName返回的是HTMLCollection集合,不能直接给集合绑定onclick或设置style,必须取集合中的单个元素(比如[0]),或者用querySelector直接获取单个元素。
  • 按钮的onclick逻辑错误:原代码用setTimeOut(拼写错误,应为setTimeout)延迟执行guessingGame,但guessingGame内部才是绑定点击事件的逻辑,导致点击按钮时根本没触发判断逻辑,反而去绑定事件,完全搞反了流程。
  • timing函数未定时循环执行:只执行一次无法实现倒计时,且函数内未定义image变量,无法修改图片模糊效果。
  • onload事件绑定错误:<div>元素不支持onload事件,应该绑定到<body>或window上。

修复后的完整代码

HTML

<html>
  <body onload="startGame()">
    <div class='isThing1'>
      <h2 id='header'>Thing 1 or Thing 2?</h2>
      <p id='safeTimerDisplay'>30</p>
      <img src='http://3.bp.blogspot.com/-KpXH9T01SHc/T0y46Pu08MI/AAAAAAAABNk/8UtrnQ0SDSM/s1600/thing1_color.png' width='230' height='240' class='thing1OrThing2'>
      <button class='thing1'>Thing 1</button>
      <p class='or'>Or</p>
      <button class='thing2'>Thing 2</button>
    </div>
  </body>
</html>

CSS

body {
  background-color: lightseagreen;
}

#header {
  position: absolute;
  left: 50px;
  color: lightskyblue;
}

.thing1 {
  position: absolute;
  top: 340px;
  left: 155px;
}

.thing2 {
  position: absolute;
  top: 410px;
  left: 155px;
}

.or {
  position: absolute;
  top: 360px;
  left: 195px;
}

.thing1OrThing2 {
  position: absolute;
  top: 70px;
  left: 100px;
  filter: blur(1.2rem);/**Sets the initial blur of the image**/
}

JavaScript

function startGame() {
  // 获取DOM元素
  const image = document.querySelector('.thing1OrThing2');
  const timerDisplay = document.getElementById('safeTimerDisplay');
  const btn1 = document.querySelector('.thing1');
  const btn2 = document.querySelector('.thing2');
  let countdown = 30;
  let timerInterval;

  // 按钮点击事件逻辑
  btn1.addEventListener('click', function() {
    clearInterval(timerInterval); // 停止倒计时
    image.style.filter = 'unset';
    alert("Correct! It's thing 1!");
  });

  btn2.addEventListener('click', function() {
    clearInterval(timerInterval);
    image.style.filter = 'unset';
    alert("Incorrect! It's thing 1!");
  });

  // 倒计时逻辑
  timerInterval = setInterval(function() {
    countdown--;
    timerDisplay.textContent = countdown;
    if (countdown === 0) {
      clearInterval(timerInterval);
      image.style.filter = 'unset';
      alert("Time's up!");
    }
  }, 1000);
}

修复说明

  1. 用querySelector替代getElementsByClassName,直接获取单个DOM元素,避免集合操作问题。
  2. 统一在startGame函数中初始化所有逻辑,页面加载(body onload)时执行该函数,一次性绑定按钮事件和启动倒计时。
  3. 修复setTimeout拼写错误,且调整按钮逻辑:点击按钮直接触发判断,不再延迟绑定事件。
  4. 倒计时用setInterval实现每秒递减,倒计时结束或用户点击按钮后清除定时器,避免内存泄漏。
  5. 修正提示文本,确保错误提示内容完整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 12:57:57