Jus*_*der 4 html javascript loops
我正在尝试使用JavaScript每隔一秒使网页更改背景颜色.我正在使用,setTimeout但我无法弄清楚如何让我的变量改变功能.这是我的代码:
 <!DOCTYPE html>
 <html>
     <head>
         <script type="text/javascript">
         function changecolors() {
             x = 1; // <-- I know this is wrong, I just don't know where to place it 
             var t = setTimeout("change()", 1000);
         }
         function change() {
             while(x < 3) {
                 if(x = 1) {
                     color = "red";
                     x++;
                 } else if (x = 2) {
                     color = "green";
                     x = 1;
                 }
                 document.body.style.background = color;
             }
         }
     </head>
     <body onload="changecolors()">
     </body>
 </html>
Ry-*_*Ry- 14
这里有几个问题.我只修复你的代码:
var x;
function changecolors() {
    x = 1;
    setInterval(change, 1000);
}
function change() {
    if (x === 1) {
        color = "red";
        x = 2;
    } else {
        color = "green";
        x = 1;
    }
    document.body.style.background = color;
}
基本上...
setInterval而不是setTimeout.setTimeout只执行一次.=甚至在if声明中指定.你需要==(或更好===).setTimeout或setInterval.相反,传递一个函数.另一点需要注意:您不应该on*将HTML元素的属性用于事件侦听器,尤其是不要使用<body>,因为您可以在JavaScript中执行此操作,并且不显眼:
window.onload = changecolors;
眨眼小提琴:
http://jsfiddle.net/GolezTrol/R4c5P/1/
使用此功能:
function initBlink()
{
    var state = false;
    setInterval(function()
        {
            state = !state;
            var color = (state?'red':'green');
            document.getElementById('test').style.color = color;
        }, 1000);
}
使用闭包来保持状态不在全局范围内.使用setInterval而不是setTimeout进行重复调用,虽然这可能不方便.如果你愿意,setInterval和setTimeout都会返回一个你可以保存并用来停止计时器的句柄,但是由于你没有问过这个问题,为了简单起见,我把它留了下来.
该函数只定义了一个匿名回调,它可以切换布尔值并设置测试div的颜色.
另外,考虑使用CSS.演示.
@-webkit-keyframes blink {
        0%   { background:red; }
        50%  { background:green;}
        100% { background:red; }
}
@-moz-keyframes blink {
        0%   { background:red; }
        50%  { background:green;}
        100% { background:red; }
}
@-ms-keyframes blink {
        0%   { background:red; }
        50%  { background:green;}
        100% { background:red; }
}
body{
     -webkit-animation: blink 1s infinite;
     -moz-animation:    blink 1s infinite;
     -ms-animation:     blink 1s infinite;
}