每秒在红色和绿色之间更改背景颜色

问题描述:

我正在尝试使网页使用JavaScript每隔一秒钟更改一次背景颜色. 我正在使用setTimeout,但是我不知道如何在函数中更改变量.这是我的代码:

I'm trying to make a webpage change the background color every one second using JavaScript. I'm using setTimeout but I can't figure out how to get my variable to change in the function. Here's my code:

 <!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>

这里有几个问题.我会修复您的代码:

There are several problems here. I’ll just fix your code:

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语句中也是如此.您需要==(或者更好的是===).
  • 您不应将字符串传递给setTimeoutsetInterval.而是传递一个函数.
  • You need setInterval instead of setTimeout. setTimeout only executes once.
  • = assigns, even in an if statement. You need == (or better, ===).
  • You shouldn't pass a string to setTimeout or setInterval. Instead, pass a function.

另一点要注意的是:您不应该将HTML元素的on*属性用于事件监听器,尤其是不要在<body>上使用,因为您可以使用JavaScript来做到这一点,而且不要太张扬:

Another point of note: you shouldn’t use the on* attributes of HTML elements for event listeners, but especially not on <body>, since you can do this in JavaScript instead, and be unobtrusive:

window.onload = changecolors;

当然,您可以用更少的功能来实现它,并且不会污染全局名称空间.

Of course, you could do it with fewer functions and no pollution of the global namespace.