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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8250647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:19:18  来源:igfitidea点击:

Change background color between red and green every second

javascripthtmlloops

提问by Justin Yoder

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

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

回答by Ry-

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;
}

Basically...

基本上...

  • You need setIntervalinstead of setTimeout. setTimeoutonly executes once.
  • =assigns, even in an ifstatement. You need ==(or better, ===).
  • You shouldn't pass a string to setTimeoutor setInterval. Instead, pass a function.
  • 你需要setInterval而不是setTimeout. setTimeout只执行一次。
  • =赋值,即使在if语句中。你需要==(或更好,===)。
  • 您不应该将字符串传递给setTimeoutor setInterval。相反,传递一个函数。

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:

另一个注意点:您不应该on*将 HTML 元素的属性用于事件侦听器,尤其是 on <body>,因为您可以在 JavaScript 中执行此操作,并且不显眼:

window.onload = changecolors;

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

当然,你可以用更少的函数和不污染全局命名空间来做到这一点

回答by GolezTrol

Blink fiddle:

闪烁小提琴:

http://jsfiddle.net/GolezTrol/R4c5P/1/

http://jsfiddle.net/GolezTrol/R4c5P/1/

Uses this function:

使用这个功能:

function initBlink()
{
    var state = false;
    setInterval(function()
        {
            state = !state;
            var color = (state?'red':'green');
            document.getElementById('test').style.color = color;
        }, 1000);
}

Uses closure to keep the state out of the global scope. Uses setInterval instead of setTimeout for repeated calling, although that may not be convenient. Both setInterval and setTimeout return a handle you can save and use to stop the timer, if you want, but since you didn't ask about that, I left it out for simplicity.

使用闭包将状态保持在全局范围之外。使用 setInterval 而不是 setTimeout 进行重复调用,尽管这可能不方便。setInterval 和 setTimeout 都返回一个句柄,您可以保存并使用它来停止计时器(如果需要),但由于您没有询问这一点,为了简单起见,我将其省略。

The function just defines an anonymous callback that toggles a boolean and sets the color of a test div.

该函数只定义了一个匿名回调,它切换布尔值并设置测试 div 的颜色。

回答by bookcasey

Also, consider doing it with CSS. Demo.

另外,考虑用 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;
}

回答by MaxArt

If you expect the browser to support CSS animations, you can so something more interesting and perhaps less annoying. Define in your style sheet:

如果您希望浏览器支持 CSS 动画,那么您可以做一些更有趣但可能不那么烦人的事情。在样式表中定义:

body {
    -webkit-animation: changebg 1s infinite cubic-bezier(1,0,0,1);
       -moz-animation: changebg 1s infinite cubic-bezier(1,0,0,1);
            animation: changebg 1s infinite cubic-bezier(1,0,0,1);
}

@-moz-keyframes changebg {
      0% {background-color: #f00;}
     50% {background-color: #fff;}
    100% {background-color: #f00;}
}

@-webkit-keyframes changebg {
      0% {background-color: #f00;}
     50% {background-color: #fff;}
    100% {background-color: #f00;}
}

@keyframes changebg {
      0% {background-color: #f00;}
     50% {background-color: #fff;}
    100% {background-color: #f00;}
}

And you're done, without JavaScript at all. Unfortunately, CSS animations are not standard yet, so those hinge on prefixes, hence I had to repeat for -moz-and -webkit-. It doesnt work on Opera and IE, for now.

大功告成,完全没有 JavaScript。不幸的是,CSS 动画还不是标准的,所以那些取决于前缀,因此我不得不重复-moz--webkit-。目前它不适用于 Opera 和 IE。

回答by Esteban Angee

You should definetly read some basic JavaScript tutorial or book. I am also new to JavaScript but some reading has helped. Here http://www.w3schools.com/js/you can find some good stuff as reference.

您绝对应该阅读一些基本的 JavaScript 教程或书籍。我也是 JavaScript 的新手,但一些阅读有所帮助。在这里http://www.w3schools.com/js/你可以找到一些好东西作为参考。

This should do the trick

这应该可以解决问题

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">

            function change_color(flag){
                var color = null;
                if (flag === true){
                    var color = "red";
                }else{
                    var color = "green";
                }
                document.body.style.background = color;
                flag = !flag
                var t=setTimeout(function(){change_color(flag)},1000);
            }
        </script>
    </head>

    <body onload="change_color(true)">
</body>

If you are going to manipulate the DOM a lot i recommend JQuery

如果您要大量操作 DOM,我建议您使用 JQuery

回答by Matt

x = 1;assigns xa value of 1, even in an ifstatement. Use x == 1in ifstatements to keep the value of your variable unchanged.

x = 1;分配x值1,即使在一个if声明。x == 1if语句中使用以保持变量的值不变。

回答by dnuttle

For one thing, this:

一方面,这是:

if (x = 1){

Should be this:

应该是这样的:

if(x == 1) {

Your statement sets x to 1, rather than tests it to see if it's 1.

您的语句将 x 设置为 1,而不是测试它是否为 1。

回答by JCOC611

I would advice not to do this, since it might be pretty annoying, but this should work:

我建议不要这样做,因为它可能很烦人,但这应该有效:

var x = false;
function changecolors(){
  var color=(x)?"green":"red"; // If X == true, then set to green, if false then blue
  document.body.style.background = color; // Set color
  x=!x; // Invert X
} 

And then in the body:

然后在体内:

<body onload="setInterval(changecolors,1000)">

PS: Sorry if I'm not answering the question right...this code will change the background from blue to green every second repeatedly for an infinite amount of time. (What I mean is that I kinda redid your code rather than explaining what was wrong with yours...)

PS:对不起,如果我没有正确回答问题......这段代码将在无限时间内重复地每秒将背景从蓝色变为绿色。(我的意思是我有点重做你的代码,而不是解释你的代码有什么问题......)

回答by Narendran Parivallal

I have created this function called toggle_colourfor the very same purpose.

出于同样的目的,我创建了这个名为toggle_colour 的函数。

function toggle_color(color1, color2, cycle_time, wait_time) { 
   setInterval(function first_color() {
       document.body.style.backgroundColor = color1;
       setTimeout(change_color, wait_time);
   }, cycle_time);

    function change_color() {
     document.body.style.backgroundColor = color2;
    }
}

Now you can simply copy the above code and call the function with two color codes. Like,

现在您可以简单地复制上面的代码并使用两个颜色代码调用该函数。喜欢,

toggle_color("#61beb3", "#90a2c6", 4000, 2000);

You can check the complete demo and more advanced toggle color functions in the article, Changing background color every X seconds in Javascript

您可以在文章中查看完整的演示和更高级的切换颜色功能,在 Javascript 中每 X 秒更改背景颜色

Disclaimer: I am the author of this tutorial article.

免责声明:我是本教程文章的作者。

回答by scartag

Your code is missing the closing </script>tag and other issues mentioned above.

您的代码缺少结束</script>标记和上述其他问题。

Find below a fix of your code that removes the global variable.

在下面找到删除全局变量的代码修复程序。

 <html> 
     <head> 
         <script type="text/javascript">
         function changecolors() {    
             var t = setInterval('change()',1000); 
         } 

         function change() {
             var color = document.body.style.background;

             if(color == "red") {
                 document.body.style.background = "green";
             } else {
                 document.body.style.background = "red";
             }
         } 
        </script>
     </head> 
     <body onload="javascript:changecolors()"> 
     </body> 
 </html>