Change background color between red and green every second

前端 未结 10 1201
终归单人心
终归单人心 2020-12-19 16:10

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 variabl

相关标签:
10条回答
  • 2020-12-19 16:43

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

    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>
    
    0 讨论(0)
  • 2020-12-19 16:46

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

    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.

    0 讨论(0)
  • 2020-12-19 16:51

    x = 1; assigns x a value of 1, even in an if statement. Use x == 1 in if statements to keep the value of your variable unchanged.

    0 讨论(0)
  • 2020-12-19 16:52

    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.

    0 讨论(0)
提交回复
热议问题