更改div的背景图片网址

时间:2016-04-30 09:45:52

标签: javascript jquery html

我有一个div我希望在背景中显示多个图像,因为通过更改css背景图像淡出淡出无法找到最佳方式。

JSFiddle

我的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;
}

3 个答案:

答案 0 :(得分:3)

使用:

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

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

而不是:

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

用于动画:

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

答案 1 :(得分:0)

像这样设置:

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

答案 2 :(得分:0)

参考此回答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++;
};