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

如何在JS计数器归零后将网页背景改为红色?自定义代码不生效求解

倒计时归零改背景色解决方案

原有代码的问题

  • 背景色修改API使用错误,不存在document.change.bgColor的写法,正确修改页面背景色的语法为document.body.style.backgroundColor = "red"
  • time变量是window.onload函数内的局部变量,你单独写的changeColor函数在外部作用域,无法访问到time的值,判断逻辑永远不生效
  • changeColor函数没有任何触发调用的逻辑,代码不会自动执行
  • 定时器没有做清除逻辑,倒计时到0后会继续执行,数值会变为负数
  • 你写在body后的第二段单独修改tag内容的代码无实际作用,window.onload执行后会直接覆盖这段逻辑的修改结果

修改后的完整可运行代码

<!DOCTYPE html>
<html>
<head>
  <title>倒计时示例</title>
</head>
<body>
  <div>
    <h1 id="tag1">Hello Earthling</h1>
  </div>

  <script>
    window.onload = function () {
      const tag = document.getElementById("tag1");
      // 倒计时初始值
      let time = 100;
      // 存储定时器ID,用于后续停止计时
      let countDownTimer = null;

      const updateTime = () => {
        time -= 1;
        tag.innerHTML = `Goodbye Aliens: ship leaves in ${time} secs `;
        
        // 归零判断逻辑
        if (time === 0) {
          // 停止定时器
          clearInterval(countDownTimer);
          // 修改页面背景为红色
          document.body.style.backgroundColor = "red";
        }
      }

      // 启动倒计时,间隔500ms即每半秒减1,要实现1秒减1可修改为1000
      countDownTimer = setInterval(updateTime, 500);
    }
  </script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 17:42:01