纯Javascript - setInterval(1s),setAttribute [英] Pure Javascript - setInterval (1s), setAttribute
问题描述
我想每秒更改一次sqaure的颜色( #myID:width = height = 100px )。 (为了检查这个开关循环是否正常工作,在每一个case中我写了 console.log(smth happen); 。)
但是颜色这个广场不会改变。 FIDDLE
接下来的事情,每一秒 document.getElementById('myID')被写入一个新的形成变量 thesquare 。
$ b
Javascript:
var i = 0;
function changecolor()
{
var thesquare = document.getElementById('myID');
switch(i)
{
case 0:
thesquare.setAttribute(background-color,red);
++ i;
休息;
案例1:
thesquare.setAttribute(background-color,green);
++ i;
休息;
默认值:
thesquare.setAttribute(background-color,blue);
i = 0;
休息;
}
}
setInterval(changecolor(),1000);
这不是您想要设置的属性,而是 style
:
thesquare.style.backgroundColor ='red';
你的函数可以工作,但属性 background-color
不做任何事情。
另外, setInterval(changecolor(),1000);
应该是 setInterval(changecolor,1000);
I'd like to change the color of the sqaure (#myID: width = height = 100px) every second. (To check if that switch loop works, in every "case" I wrote console.log("smth happened");.) But the color of this square does not change. "FIDDLE"
Next thing, every second document.getElementById('myID') is written to a new formed variable thesquare. How to make the variable global, outside the function?
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);
It is not an attribute you want to set but a style
:
thesquare.style.backgroundColor = 'red';
Your function does work but the attribute background-color
does not do anything.
Also, setInterval("changecolor()",1000);
should be setInterval(changecolor,1000);
这篇关于纯Javascript - setInterval(1s),setAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!