如何在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
相关产品推荐
相关产品推荐

