【问题标题】:Pure Javascript - setInterval (1s), setAttribute纯 Javascript - setInterval (1s), setAttribute
【发布时间】:2014-08-08 15:31:35
【问题描述】:

我想每秒更改一次正方形的颜色 (#myID: width = height = 100px)。 (为了检查开关循环是否有效,在每个“案例”中我都写了 console.log("smth occurred");。) 但是这个正方形的颜色并没有改变。 "FIDDLE"

接下来,每隔一秒 document.getElementById('myID') 都会写入一个新形成的变量 thesquare。如何在函数之外使变量成为全局变量?

Javascript:

var i = 0;
function changecolor()
{       
    var thesquare = document.getElementById('myID');
    switch (i)
    {
        case 0 :
        thesquare.setAttribute("background-color","red");
        ++i;
        break;

        case 1 :
        thesquare.setAttribute("background-color","green");
        ++i;
        break;

        default :
        thesquare.setAttribute("background-color","blue");
        i=0;
        break;
    }
}
setInterval("changecolor()",1000);

【问题讨论】:

  • setInterval(changecolor,1000);
  • 这个“ javascript怎么样?它使用DOM api。
  • 纯 Javascript - 无 jQuery
  • @Bergi 我想你明白他想要表达的意思。我想这意味着在这种情况下“没有框架”。

标签: javascript animation global-variables setinterval


【解决方案1】:

这不是你要设置的属性,而是style:

thesquare.style.backgroundColor = 'red';

您的函数确实有效,但属性background-color 没有任何作用。

另外,setInterval("changecolor()",1000); 应该是 setInterval(changecolor,1000);

Fiddle

【讨论】:

  • @GovindSinghNagarkoti 该方法使用 eval,应该避免。 putvande 的建议更合适。
【解决方案2】:

接下来,每隔一个 document.getElementById('myID') 被写入 一个新形成的变量 thesquare。如何使变量全局化, 在函数之外?

您不需要使用全局,您可以使用闭包和立即调用的函数表达式 (IIFE) 将其保持在外部范围内:

(function() {
  var thesquare = document.getElementById('myID');
  var i = 0;

  function changecolor() {
    switch (i) {
        case 0 :
          thesquare.style.backgroundColor = "red";
          ++i;
          break;

        case 1 :
          thesquare.style.backgrounColor = "green";
          ++i;
          break;

        default :
          thesquare.style.backgroundColor = "blue";
          i=0;
          break;
    }
  }
  setInterval(changecolor, 1000);
}());

请注意,setInterval 将按指定的时间间隔运行,但并不完全如此。它会慢慢失去时间。

您可以通过将整个 switch 块替换为以下内容来缩短代码:

   var colours = ['red','green','blue']
   thesquare.style.backgroundColor = colours[i++ % colours.length];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    相关资源
    最近更新 更多