Change Background Color CSS with Timer JQuery

后端 未结 2 1509
情话喂你
情话喂你 2020-12-10 20:53

I was hoping someone could show me efficient JQuery to animate between 4 background colors in a div class.

I would like these events to be triggered by time, not cli

相关标签:
2条回答
  • 2020-12-10 21:45

    UPDATE

    I'm sure there are better ways to do this, but just to show you a simple way of accomplishing this...

    http://jsfiddle.net/UnsungHero97/QLPbW/5/


    You want to use the window.setInterval() function...

    window.setInterval(rotateBG, 1000); // 1000 = 1 second
    
    function rotateBG() {
        // logic to rotate background
    }
    

    I hope this helps.

    0 讨论(0)
  • 2020-12-10 21:49

    I dont know if you mean animated as in fading to the next, but heres a simple quick example of changing the color every 2 seconds. First example does not require jQuery.

    Live Demo

    function changeColor(curNumber){
        curNumber++;
    
        if(curNumber > 4){
            curNumber = 1;
        }
        document.body.setAttribute('class', 'color' + curNumber);
        setTimeout(function(){changeColor(curNumber)}, 2000);  
    }
    
    changeColor(0);
    

    Update animating color

    Second example requires Jquery UI if you wish to fade between classes or background colors.

    Demo 2

    function changeColor(element, curNumber){
        curNumber++;
    
        if(curNumber > 4){
            curNumber = 1;
        }
    
        element.addClass('color' + curNumber, 1000);
    
        // So previous classes get removed.
        element.attr('class', 'color' + curNumber);
    
        setTimeout(function(){changeColor(element, curNumber)}, 2000);  
    }
    
    changeColor($('#testElement'), 0);
    
    0 讨论(0)
提交回复
热议问题