每秒在红色和绿色之间更改背景颜色 [英] Change background color between red and green every second

查看:107
本文介绍了每秒在红色和绿色之间更改背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使网页使用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.

这篇关于每秒在红色和绿色之间更改背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆