DIV - 替代背景图像

Gre*_*reg 1 html javascript css jquery

我没有实现滑块插件,而是想使用CSS/jquery来交替DIV的背景图像(fadein/fadeout或slide effect).目前我的代码如下:

HTML

<div class="block backpic">
</div>
Run Code Online (Sandbox Code Playgroud)

CSS

.block {

    display: block;
        margin-right: auto;
    margin-left: auto;
    clear: both;
    box-sizing: border-box;
    padding-left: 20px;
    padding-right: 20px;
    width: 100%;
    overflow: hidden;
}


.backpic {
    height: 638px;
    background-image: url(../images/picture1.jpg);
    background-size: cover;
}
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能将picture1与第二张图片交替?非常感谢您的帮助

she*_*nan 6

使用jQuery淡化元素,而不是更改它的background-image属性,然后再次淡入:

$('.block').fadeOut(300, function(){

  $(this).css('background-image', 'url(path/to/other/image.jpg)')

  $(this).fadeIn(300);

});
Run Code Online (Sandbox Code Playgroud)

如果你想要一个像幻灯片一样的动画循环,使用JavaScript setInterval方法让代码在一定的毫秒后重复:

var images = [

  'path/to/image1.jpg',
  'path/to/image2.jpg',
  'path/to/image3.jpg'

];

var index = 0;

setInterval(change_up, 1000);

function change_up(){

  index = (index + 1 < images.length) ? index + 1 : 0;

  $('.block').fadeOut(300, function(){

    $(this).css('background-image', 'url('+ images[index] + ')')

    $(this).fadeIn(300);

  });
}
Run Code Online (Sandbox Code Playgroud)

这是一个例子