背景图像循环 - 具有平滑淡入淡出或过渡的z索引

时间:2017-03-20 10:59:32

标签: jquery html css

我意识到有一些类似的问题,但请听我说。我问,因为其他答案还没有让我找到解决方案。

这是我的小提琴:https://jsfiddle.net/k6z22kns/

我可以让图像循环,但我真的在努力让它们淡化或平滑过渡。现在它只是从一个图像跳到另一个图像,你可以在小提琴中看到。我已尝试使用fadeIn回调动画,而其他任何东西,但我无法做到正确。这整个上午一直在杀我。

var imageIndex = 0;
var imagesArray = ["https://www.gstatic.com/webp/gallery/1.sm.jpg","https://www.gstatic.com/webp/gallery/2.sm.jpg","https://www.gstatic.com/webp/gallery/3.sm.jpg","https://www.gstatic.com/webp/gallery/5.sm.jpg"];

function changeBackground(){
  var index = imageIndex++ % imagesArray.length;
  $(".bsh-images").eq(index).css({"z-index":"-997"});
  $(".bsh-images").eq(index-1).css({"z-index":"-998"});

}

$(document).ready(function() {
  setInterval(changeBackground, 5000);
});

1 个答案:

答案 0 :(得分:0)

您可以通过使用过渡/动画简单地创建动画效果。在此示例中,我最初将图像的opcaity设置为零,然后将显示图像的不透明度更改为1.并为css中的图像添加了过渡。 或者你可以找到很多插件来创建这些类型的图像滑块

var imageIndex = 0;
var imagesArray = ["https://www.gstatic.com/webp/gallery/1.sm.jpg", "https://www.gstatic.com/webp/gallery/2.sm.jpg", "https://www.gstatic.com/webp/gallery/3.sm.jpg", "https://www.gstatic.com/webp/gallery/5.sm.jpg"];

function changeBackground() {
  var index = imageIndex++ % imagesArray.length;

  $(".bsh-images").eq(index).css({
    "z-index": "-997"
  }).addClass('show');
  $(".bsh-images").eq(index - 1).css({
    "z-index": "-998"
  }).removeClass('show');

}

$(document).ready(function() {
  setInterval(changeBackground, 3000);
});
.bsh-images {
  height: 100%;
  width: 100%;
  position: absolute;
  top: 0px;
  z-index: -998;
  display: block;
  opacity: 0;
  -webkit-transition: opacity 2s ease-in;
  -moz-transition: opacity 2s ease-in;
  -ms-transition: opacity 2s ease-in;
  -o-transition: opacity 2s ease-in;
  transition: opacity 2s ease-in;
}

.bsh-images.show {
  opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bs-bg-slides">
  <div class="bsh-images bsh-image-1 show" style="background: url(https://www.gstatic.com/webp/gallery/1.sm.jpg) center center / cover no-repeat;"></div>
  <div class="bsh-images bsh-image-2" style="background: url(https://www.gstatic.com/webp/gallery/2.sm.jpg) center center / cover no-repeat; "></div>
  <div class="bsh-images bsh-image-3" style="background: url(https://www.gstatic.com/webp/gallery/3.sm.jpg) center center / cover no-repeat;"></div>
  <div class="bsh-images bsh-image-4" style="background: url(https://www.gstatic.com/webp/gallery/5.sm.jpg) center center / cover no-repeat;"></div>
</div>