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

用JS/CSS/HTML制作糖果消消乐结束界面:计时器到0无触发问题

问题分析与修复方案

核心问题拆解

  • 变量作用域隔离:seconds是timer函数内部的局部变量,endGame函数根本访问不到它,导致seconds === 0的条件永远不成立。
  • 结束逻辑未触发:endGame函数从未被调用,计时器归0时没有执行任何结束判断的操作。
  • 计时器数值判断错误:原逻辑里是先执行seconds--,再判断seconds < 0才停止计时器,此时seconds的值是-1,不是0,原条件seconds === 0完全匹配不到。
  • 缺少界面显示代码:就算条件满足,当前代码只是打印endWindow1,没有修改结束界面的display属性来让它从隐藏变为显示。
  • score变量未明确作用域:如果score是其他函数的局部变量,endGame同样无法访问,必须确保它是全局或在同一作用域内。

修正后的代码示例

JavaScript代码

// 把关键变量设为全局,确保endGame能访问
let seconds = 120;
let timer;
// 假设score是全局变量,实际游戏中由你的得分逻辑更新
let score = 0;

function startTimer() {
  timer = setInterval(function() {
    document.getElementById("safeTimerDisplay").innerHTML = seconds;
    // 先判断是否到0,再执行减秒逻辑
    if (seconds === 0) {
      clearInterval(timer);
      endGame(); // 计时器归0时立刻触发结束逻辑
    }
    seconds--;
  }, 1000);
}

function endGame() {
  if (score > 1800) {
    // 显示结束界面
    const endWindow = document.getElementById("EndWindow1");
    endWindow.style.display = "block";
    // 可以在这里添加禁用游戏操作、展示最终分数等逻辑
    document.getElementById("finalScore").textContent = score;
  } else {
    // 分数未达标时的逻辑,比如显示失败提示
    console.log("分数未达到1800,无法解锁结束界面");
  }
}

// 启动计时器
startTimer();

CSS代码(优化全屏覆盖效果)

#EndWindow1 {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url("./endscreen.jpg") no-repeat center center fixed;
  background-size: cover;
  font-family: Arial, Helvetica, sans-serif;
  color: white;
  text-align: center;
  display: none; /* 默认隐藏 */
}

HTML代码(补充结束界面内容)

<div id="EndWindow1">
  <h2>恭喜通关!</h2>
  <p>你的最终得分:<span id="finalScore"></span></p>
</div>
<h1>Timer: <span id="safeTimerDisplay"></span></h1>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:51:27