繁体   English   中英

Javascript使用settimeout更改背景颜色

[英]Javascript change background color using settimeout

我正在设计一个鱼缸。 页面的整个背景是水。 我想设置一个函数,在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),然后运行脏功能。 除非用户单击按钮,然后进行清洗,然后再等待5秒钟再变脏,否则什么都不会发生。 简单,干净,有效。 :D

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM