Change the body background image with fade effect in jquery

后端 未结 7 1618
说谎
说谎 2020-12-01 09:40

Hey i want to fade in a new background image let´s say every 60 seconds. I´ve set the background image like this:

body {background-image: url(background.jpg)         


        
7条回答
  •  有刺的猬
    2020-12-01 10:26

    You can use the setInterval method and switch between classes defined in your CSS which have different background-images:

    setInterval(function() {
        var $body = $('body');
        if($body.hasClass('background1'))
        {
            $body.removeClass('background1');
            $body.addClass('background2');
        }
        else {        
            $body.removeClass('background2');
            $body.addClass('background1');
        }
    }, 1000);
    

    Fiddle

    This example uses an interval of 1000 which is one second. You can change this value for whatever period of time you're looking for.

    UPDATE

    Noticed your question asked for a fade so I added a CSS3 property on body:

    body
    {
        transition: background 0.5s linear;
    }
    

    The fiddle has been updated.

提交回复
热议问题