DIV - 备用背景图像

DIV - Alternate background images

本文关键字:图像 背景 备用 DIV      更新时间:2023-09-26

我想使用 CSS/jquery 来替代 DIV 的背景图像(淡入/淡出或幻灯片效果),而不是实现滑块插件。目前我的代码如下:

.HTML

<div class="block backpic">
</div>

.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;
}

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

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

$('.block').fadeOut(300, function(){
  $(this).css('background-image', 'url(path/to/other/image.jpg)')
  $(this).fadeIn(300);
});

如果你想要一个类似幻灯片的动画循环,请使用 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);
  });
}

下面是一个示例

尝试使用偶数和奇数选择器

    .block:nth-child(odd) {
background-image:
 height: 638px;
    background-image: url(../images/picture1.jpg);
    background-size: cover;
}
.block:nth-child(even) {
background-image:
 height: 638px;
    background-image: url(../images/pictureNew.jpg);
    background-size: cover;
}

有一个核心滑块类

.slider{
   opacity:1
   -webkit-transition:opacity 500ms;
   -moz-transition:opacity 500ms;
   -ms-transition:opacity 500ms;
   transition:opacity 500ms;
}
.hideSlide{
   opacity:0
}

这将导致不透明度的淡出。然后,您可以使用隐藏幻灯片类更改不透明度,并在透明时更改背景图像。然后删除隐藏幻灯片类,它将淡入。

或者,您可以将一堆div 放在彼此之上,以增加 500ms 1000ms、1500ms 等的长度淡出,以将它们暴露给观众。