Change background color between red and green every second

前端 未结 10 1243
终归单人心
终归单人心 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:38

    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:

    
    

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

提交回复
热议问题