动画序列变得干扰

时间:2016-05-10 14:17:35

标签: javascript jquery

我有一系列图像渐渐消失然后回到其中似乎适用于大约2个循环。不幸的是,它变得疯狂,序列似乎完全随机。

我做了一个小提琴,所以你可以看到https://jsfiddle.net/MichaelCaley/Lmm3kp4m/

上发生了什么
var imgshow = function(){
    $(".img1").delay(2000).animate({
        opacity: 0
    }, 3000, function(){
        $(".img2").delay(2000).animate({
            opacity: 0
        }, 3000, function(){
            $(".img3").delay(2000).animate({
                opacity: 0
            }, 3000, function(){
                $(".img1").delay(2000).animate({
                    opacity: 1
                }, 3000, function(){
                    $(".img2, .img3").animate({
                        "opacity": "1"
                    }, 0, function(){
                        imgshow();
                    });
                });
            });
        });
    });
}

imgshow();

在第一次运行之后,我已经完成了一个重置​​步骤,这应该是2个类同时更改的唯一时间,但是当我观察循环时,我开始看到多个div开始在整个过程中逐渐消失,我无法理解。

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

在回调地狱中很容易混淆或丢失,特别是对于jQuery动画,特别是在使用delay时。至少在我看来,我可以建议一些更干净的东西。

// Get all images that need to be looped.
var images = $('.some-class-all-images-share');
// Create an array to store images that have already been shown.
var cycled = $([]);
// Start an interval, which calls the same function every 5 seconds.
setInterval(function(){
  // Get the first image from the images array.
  var image = images.unshift();

  // If the images array is empty, reset everything.
  if (images.length === 0) {
    images = cycled;
    cycled = $([]);
    images.removeClass('transparent');
  }
  // Add a the class 'transparent' to the image.
  image.addClass('transparent');
  // Add the image to the cycled images array.
  cycled.add(image);
}, 5000);

在CSS中:

.some-class-all-images-share {
  /* This means that whenever the opacity of the element changes, it will do so gradually, over three seconds, instead of instantly.*/
  transition: opacity 3s;
}

.transparent {
  opacity: 0;
}

现在每个图像都将逐个应用透明类。这将触发一个三秒长的动画,当除最后一个之外的所有图像都已动画时,它将重新启动。 通过这种方式,您不需要为每张图片进行另一次回调,而且应该更加易于管理。

相关问题