Javascript 使用 settimeout 更改背景颜色

Javascript change background color using settimeout

本文关键字:背景 颜色 使用 settimeout Javascript      更新时间:2023-09-26

我正在设计一个鱼缸。页面的整个背景是水。我想设置一个函数,在 5000 毫秒后将水从蓝色更改为棕色,然后暂停。然后,用户将单击一个按钮以"清洁水箱",这将重置背景更改功能。

我能找到的唯一解决方案是继续将背景从蓝色更改为绿色的循环。

var intPgColorIndex = 0;
var arrPgColor = new Array("#999966", "#00ffff" );
function SetPgColor()
{
var PgColor;
intPgColorIndex++;
if (intPgColorIndex >= arrPgColor.length)

{
intPgColorIndex = 0;
}
PgColor = arrPgColor[intPgColorIndex];
if (PgColor = "#999966" ) {
 document.body.style.backgroundColor = PgColor;
 setTimeout("SetPgColor()", 5000);
 }

  };

阻止代码按预期运行的唯一部分是使用=而不是==来比较值。

但是,你的代码又丑又糟糕,所以这里有一个更好的版本:

setTimeout(function dirty() {
    document.body.style.backgroundColor = "#996";
    var btn = document.body.appendChild(document.createElement('button'));
    btn.appendChild(document.createTextNode("Clean the tank"));
    btn.onclick = function clean() {
        btn.parentNode.removeChild(btn);
        document.body.style.backgroundColor = "#0ff";
        setTimeout(dirty,5000);
    };
},5000);
function clean() {
  clearTimeout(dirt);
  var dirt = setTimeout(dirt, 5000)
  //set color to blue
}
function dirt() {
  //set color to brown
}

在程序开始时调用 clean,并在用户单击按钮或其他内容时执行它。它将等待 5 秒(有点短的 imo),然后运行 dirt 功能。在用户单击按钮之前,不会发生任何事情,此时水箱被清洁,然后再次等待 5 秒钟,然后再次变脏。简单、干净、有效。:D