简体   繁体   中英

Change Background image url of div

i have a div for which i want to show multiple images in the background as a fade in fade out by changing the css background image am unable to find the best way.

JSFiddle

My HTML:

<div id="background"></div>

Jquery

var bgArr = ["http://malsup.github.io/images/p1.jpg", "http://malsup.github.io/images/p1.jpg", "images/TopImage-03.jpg"];
var i = 0;

// Start the slide show
var interval = self.setInterval("swapBkgnd()", 5000)

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

CSS:

#background {
  position: absolute;
  min-height: 100%;
  width: 100%;
  height: auto;
  top: 0;
  left: 0;
  background: url(http://2.bp.blogspot.com/-ayEwJpMGTPQ/USqliwPWo1I/AAAAAAAAHtI/ab6NHVy0Q48/s1600/tree.jpg) no-repeat center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

Use:

Jsfiddle: http://jsfiddle.net/ook3ah4p/

var interval = self.setInterval(swapBkgnd, 5000) // true syntax

instead of:

var interval = self.setInterval("swapBkgnd()", 5000) // wrong syntax

for animation:

$('#background')
    .animate({opacity: 0}, 'slow', function() {
        $(this)
            .css({'background-image': "url(" + bgArr[i] + ")"})
            .animate({opacity: 1});
    });

Set it up like this:

function swapBkgnd() {
  if (i > (bgArr.length - 1)) {
    i = 0;
  }
  $("#background").fadeOut("slow", function () {
    $(this).css("background-image", "url(" + bgArr[i] + ")");
    $(this).fadeIn("slow");
  });
  i++;
};

Refering to this answer How to fade changing background image

var interval = self.setInterval(swapBkgnd, 5000)

function swapBkgnd() {
    if (i > (bgArr.length - 1)) {
        i = 0
        $('#background').fadeTo('slow', 0.3, function(){
            $(this).css('background-image', 'url(' + bgArr[i] + ')');
        }).fadeTo('slow', 1);
    } else {
        $('#background').fadeTo('slow', 0.3, function(){
            $(this).css('background-image', 'url(' + bgArr[i] + ')');
        }).fadeTo('slow', 1);
}
i++;
};

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