首页 > 解决方案 > animate.css 循环 2 个不同的动画

问题描述

我最近在我的最新项目中遇到了 animate.css 的问题。

基本上我想要做的是用 jQuery 每五/十秒刷新一次网页上的段落文本,但我不想简单地更改文本。我希望以前的文本使用 animate.css fadeOut动画消失,而新的文本使用fadeIn动画出现。

目前我正在使用这个代码(只是一个例子):

setInterval(function() {
  $("#myp").addClass('fadeOut');
  $("#myp").text(sometext);
  $("#myp").removeClass('fadeOut');
  $("#myp").addClass('fadeIn');
  $("#myp").removeClass('fadeIn');
}, 5000);

显然sometext,为简单起见,每个周期都不同。

起初,这段代码给了我一些问题,因为动画不流畅而是闪烁。我试图通过在添加和删除类之间使用休眠程序来减慢该过程setTimeout,因为我认为在 css 动画结束之前删除类可能会导致问题但仍然闪烁。

标签: javascriptcssanimationbootstrap-4

解决方案


您可以在函数内嵌套一些setTimeOut方法setInterval
所以你可以控制动画每一步的时间。

此外,由于 animate.css 使用animation属性,还需要确定 CSS 中的animation-durationand animation-fill-mode

animation-duration指定动画周期应该花费多长时间。
animation-fill-mode使用“forwards”将防止元素在动画完成后重置为先前的状态。

var sometext = "another text";

setInterval(function() {
  
    var myp = $("#myp");
    myp.addClass('fadeOut');
  
    setTimeout(function() {
      myp.text(sometext);
      myp.removeClass('fadeOut');
      myp.addClass('fadeIn');
      
      setTimeout(function() {
         myp.removeClass('fadeIn');
      }, 1000);
      
    }, 1000);
  
}, 5000);
#myp {
  animation-duration: 1s;
  animation-fill-mode: forwards;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myp">lorem ipsum dolor sit</div>


推荐阅读