【问题标题】:Javascript change background color using settimeoutJavascript使用settimeout更改背景颜色
【发布时间】:2013-01-31 02:47:09
【问题描述】:

我正在设计一个鱼缸。页面的整个背景是水。我想设置一个功能,在 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);
 }


  };

【问题讨论】:

  • 你为什么不展示你发现的东西。
  • 听起来不错。迫不及待想看到您的代码。
  • 麻烦这里if (PgColor = "#999966" ) {一定是==,这里setTimeout("SetPgColor()",,最好用setTimeout(SetPgColor,
  • 除了改变颜色的方式之外,您还有正确的想法。例如,迭代 ajax 就是一个时间循环。不要回避这一点。

标签: javascript html background timer settimeout


【解决方案1】:

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

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

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);

【讨论】:

  • 非常感谢。我还在学习中,所以我的代码可能看的头疼!我真的很感谢你的帮助! :)
【解决方案2】:
function clean() {
  clearTimeout(dirt);
  var dirt = setTimeout(dirt, 5000)
  //set color to blue
}
function dirt() {
  //set color to brown
}

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

【讨论】:

  • 拥有同名的变量和函数会有点混乱。我建议重命名其中一个。也许是var timer
  • 嗯,是的,我会使用dirtyTimer或其他东西,但我没有意识到我使用了两次相同的东西。你可以告诉它凌晨 3:30 :P
猜你喜欢
  • 2023-03-28
  • 1970-01-01
  • 2015-06-23
  • 2010-09-16
  • 2013-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
相关资源
最近更新 更多