首页 > 解决方案 > 在一个数据属性中为背景图像设置动画

问题描述

我尝试在这些背景图像 url 之间创建一个漂亮的动画,它们存在于一个数据属性中(第一张图像立即加载,5 秒后加载下一张图像,下一张等。在最后一张之后,它从头开始)。

<div data-images="/media/jtjglhbb/main-bg-01.jpg,/media/u2bitolk/main-bg-02.jpg,/media/iasbuo5n/main-bg-04.jpg,/media/f00jm2va/main-bg-03.jpg,"></div>

var $dataImages = $('[data-images]');
var imagesList = $dataImages.data('images').split(',');

$.each(imagesList, function (index, value) {
    setTimeout(function () {
        $dataImages.stop().animate({ opacity: 0 }, 1000, function () {
            $(this).css({ 'background-image': 'url(' + imagesList[index] + ')' })
                .animate({ opacity: 1 }, { duration: 1000 });
        });
    }, 5000);
});

但它没有设置第一个图像,它只在 5 秒后开始,并且它完全不是一个一个地运行,有 5 秒的延迟。

显然逻辑是错误的,一些帮助会很棒。

标签: javascriptjquery

解决方案


尝试如下。它应该工作。

  1. 需要图像计数才能使模式值重新开始。
  2. index将保存图像的索引以在背景中显示
  3. changeImage函数将从内部递归调用,因此它将不断更新背景。
  4. 使用index = (index + 1) % imageCount;所以索引将从最后一个索引再次从 0 开始。

var $dataImages = $('[data-images]');
var imagesList = $dataImages.data('images').split(',');
// image count will required to get mode value to start from beginning again.
var imageCount = imagesList.length - 1;
// index of image to show in background
var index = 0;

// function will be called recursively from inside so it will continuously update background.
function changeImage() {

  $dataImages.stop().animate({
    opacity: 0
  }, 1000, function() {
    $(this).css({
        'background-image': 'url(' + imagesList[index] + ')'
      })
      .animate({
        opacity: 1
      }, {
        duration: 1000
      });
  });

  // update index to next image url
  index = (index + 1) % imageCount;

  // declare timeout to call function after required time
  setTimeout(changeImage, 5000);
}

changeImage();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

<div style="height: 150px;" data-images="https://www.w3schools.com/howto/img_nature_wide.jpg,https://www.w3schools.com/howto/img_snow_wide.jpg,https://www.w3schools.com/howto/img_lights_wide.jpg,https://www.w3schools.com/howto/img_mountains_wide.jpg"></div>


推荐阅读