简体   繁体   中英

Fade my background change

I have to change a div bg each 5 seconds.

But I really want to make this transition as a fade effect..

I'm doing this (but I get an abrupt transition instead of a fade one...):

<script>
var bgArr = ["images/1.jpg", "images/2.jpg", "images/3.jpg" ]; 
var i=0;
var interval = self.setInterval("changeBg()", 5000)  

function changeBg() {
 if (i>(bgArr.length-1) ) {
  i=0
  $("#header").css("background-image", "url("+bgArr[i]+")");
 }
 else {
  $("#header").css("background-image", "url("+bgArr[i]+")"); 
 } 
 i++;
};


</script>

How can I do this transition as a fade... without showing a white space (I mean.. The second image appears slowly over the first one)??

I'm really stuck.. :(

You can try the bgshuffle script. It uses JqueryUI. You will have to include JqueryUI somewhere in your page. The script is posted on github, feel free to extend it if you like:

https://github.com/vikaskumarsingh123/bgshuffle/

You can simply call it like :

shuffleBG( ['1.jpg','2.jpg','3.jpg','4.jpg','5.jpg'] );//the array of wallpapers

or Advanced Usage:

shuffleBG(['1.jpg','2.jpg','3.jpg','4.jpg','5.jpg'], //the array of wallpapers
        '10000', //time between wallpaper change, defaults to 10000ms (10secs)
        '1000', //fade in fade out animation speed, defaults to 1000ms
        'white' //color to fade in and out of, defaults to body backgroundColor or white
);

You will usually be calling this function on document.load and it will start changing the background image fade-in-out every 10 seconds.

How about using .fadeTo() :

DEMO: https://jsfiddle.net/w13bhcgt/

$(function () {
    var bgArr = ['http://png-5.findicons.com/files/icons/1243/hello_kitty/256/flower.png',
        'http://www.vectorimages.org/01/01201101251549265911.png',
        'http://media.janm.org/exhibitions/hellokitty/JANM-HelloKitty-icon-bow.png'];

    var i = 0;

    function Change() {
        $("#header")
            .fadeTo('slow', 1)
            .css("background-image", "url(" + bgArr[i] + ")")
            .fadeTo('slow', 0);
        i++;
        if (i < bgArr.length) setTimeout(Change, 2000);
    }
    Change(0);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM