纯Javascript - setInterval(1s),setAttribute

Kar*_*daw 1 javascript animation global-variables setinterval

我想每秒更改sqaure的颜色(#myID:width = height = 100px).(为了检查切换循环是否有效,在每个"case"中我写了console.log("smth happen");.) 但是这个方块的颜色不会改变."小提琴"

接下来,每隔一个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);
Run Code Online (Sandbox Code Playgroud)

put*_*nde 5

它不是您要设置的属性,而是style:

thesquare.style.backgroundColor = 'red';
Run Code Online (Sandbox Code Playgroud)

您的功能确实有效,但该属性background-color不起作用.

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

小提琴