使用jQuery实现循环延迟无限CSS3动画

3
我正在尝试在动画元素上添加和删除类,以创建错开/延迟效果,因此一旦完成动画,它会添加一个动画输出类,然后一旦完成该类,它就重新启动该过程。
我正在使用animate.css进行动画。
我在这里创建了一个jsFiddle:https://jsfiddle.net/3ozfgrh2/ 正如您所看到的,它很好地播放了第一个“循环”,但然后它会过早/关闭删除/添加类。
var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
$('.sticker').on(animationEnd, function() {
    var $this = $(this);
    $this.removeClass('bounceIn').addClass('bounceOut').on(animationEnd, function() {
        setTimeout(function() {
            $this.removeClass('bounceOut').addClass('bounceIn');
        }, 1000);
    });
});

任何想法?
1个回答

1
看起来代码不能按您的预期工作,因为您试图将两种不同的行为附加到同一个“onAnimationEnd”事件上。您可以通过使用 .off() 取消连接到animationEnd事件的任何事件,然后再使用 .on() 附加新行为来避免此混淆。
我已将您的代码拆分为两个单独的函数,以便您可以将它们设置为在循环中继续持续触发。

var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';

$('.sticker').on(animationEnd, addBounceOut);

function addBounceOut() {
    var $this = $(this);
    $this.removeClass('bounceIn').addClass('bounceOut').off(animationEnd).on(animationEnd, addBounceIn);
}

function addBounceIn() {
    var $this = $(this);
    setTimeout(function () {
        $this.removeClass('bounceOut').addClass('bounceIn').off(animationEnd).on(animationEnd, addBounceOut);
    }, 1000);
}
.sticker {
  display: inline-block;
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center center;
  width: 12vw;
  height: 12vw;
  position: absolute;
  z-index: 1;
  animation-duration: 1s;
}

.sticker.one {
  background-color: orange;
  top: 7%;
  left: 15%;
  animation-delay: 1s;
}

.sticker.two {
  background-color: green;
  top: 14%;
  right: 11%;
  animation-delay: 2s;
}

.sticker.three {
  background-color: blue;
  top: 43%;
  right: 22%;
  animation-delay: 3s;
}

.sticker.four {
  background-color: red;
  top: 60%;
  left: 10%;
  animation-delay: 4s;
}
<link href="https://cdn.rawgit.com/daneden/animate.css/master/animate.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="sticker one animated bounceIn" href="#"></a>
<a class="sticker two animated bounceIn" href="#"></a>
<a class="sticker three animated bounceIn" href="#"></a>
<a class="sticker four animated bounceIn" href="#"></a>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接