Change background color between red and green every second

前端 未结 10 1240
终归单人心
终归单人心 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条回答
  •  萌比男神i
    2020-12-19 16:37

    I have created this function called toggle_colour for the very same purpose.

    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

    Disclaimer: I am the author of this tutorial article.

提交回复
热议问题