【问题标题】:How can i implement a for loop to animate using anime.js我如何使用anime.js实现一个for循环来制作动画
【发布时间】:2018-03-04 12:18:09
【问题描述】:

我正在尝试使用 JQuery 和框架 anime.js 为我的页面加载器实现一个 for 循环

    var testimonialElements = $(".loader-animation");
    for(var i=0; i< Elements.length; i++){
        var element = Elements.eq(i);
        //do something with element
    
         var basicTimeline = anime.timeline();
           basicTimeline
      .add({
        targets: element,
        opacity: {
        value: ['1','0'],
        duration: 2000,
        delay: 4000
      },
      letterSpacing: {
        value: ['30px','10px'],
        duration: 2000,
        easing: 'easeInOutSine'
      }
    });
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container on-loader">	
    	<h2 class="loader-animation">Case1</h2>
    <h2 class="loader-animation">Case2</h2>
    <h2 class="loader-animation">Case3</h2>
    <h2 class="loader-animation">Case4</h2>
    </div>

问题是,脚本没有循环并为每个循环启动动画。

非常抱歉,如果问题很简单,我是 javascript 和anime.js 框架的新手。

【问题讨论】:

  • 您想为每个文本一个接一个地制作动画?
  • 是的,一个接一个
  • 我面临的问题是为每个循环初始化动画
  • 检查我的答案

标签: javascript jquery anime.js


【解决方案1】:

没有必要使用循环,首先你将.loader-animation 选择器传递给你的动画,你只需要使用callback 函数,它返回当前元素和所有元素之间的顺序(1 ,2,3. ...) 并将延迟乘以最后一个: (以后你可以玩上延迟秒来甜蜜你的意图)

请参阅下面的工作片段

var basicTimeline = anime.timeline();
basicTimeline.add({
  targets: ".loader-animation",
  opacity: {
    value: ['1', '0'],
    duration: 2000,
    delay: function(el, i) {
      $(el).removeClass("otherclass");
      return 2000 * (i + 1);
    },
  },
  letterSpacing: {
    value: ['30px', '10px'],
    duration: 2000,
    easing: 'easeInOutSine',
    delay: function(el, i) {
      return 2000 * (i);
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.2.0/anime.js"></script>
<div class="container on-loader">
  <h2 class="loader-animation otherclass">Case1</h2>
  <h2 class="loader-animation otherclass">Case2</h2>
  <h2 class="loader-animation otherclass">Case3</h2>
  <h2 class="loader-animation otherclass">Case4</h2>
</div>

【讨论】:

  • 非常感谢,像魅力一样工作。只有一个问题。
  • 让我们假设对于 .loader-animation 中的每个 [i] 我需要切换与 .loader-animation 存在的类。如果我没有错的话,这不会很好。
  • 另外,如果你能解释一下为什么上面的 for 循环出错了,那将是最好的。
  • 好吧,因为你可以删除类,在回调函数中,看我更新的答案,你只需要包装返回元素(el)并删除所需的类。
  • 对于您的示例,首先在动画中 js 目标必须是选择器而不是节点,因此如果尝试通过 for 循环访问示例,您只需将每个循环的目标设置为 @987654325 @ ,在这种情况下,所有的动画都会同时触发。
猜你喜欢
  • 1970-01-01
  • 2020-09-22
  • 1970-01-01
  • 2023-01-10
  • 1970-01-01
  • 2022-01-01
  • 2020-08-10
  • 2020-02-04
  • 1970-01-01
相关资源
最近更新 更多