【问题标题】:anime.js - how to call animation from multiple buttons (same class)Anime.js - 如何从多个按钮调用动画(同一类)
【发布时间】:2021-07-10 08:06:19
【问题描述】:

我正在尝试使用播放按钮调用 anime.js 动画。该文档解释了如何仅使用单个按钮 (querySelector) 播放动画,但我需要从不同的按钮播放相同的动画。

我尝试使用querySelectorAll 而不是单个querySlector 编写函数,但未成功:

 var animation = anime({
  targets: '.reds',
  translateX: ['-100%', '100%'],
  duration: 1600,
  easing: 'easeInOutQuad',
  autoplay: false,
});

var oks = document.querySelectorAll(".correct");

for(x=0; x<oks.length; x++){
    var ok = oks[x];
  ok.addEventListener("click", function(){
    animation.play;
  });
}

anime.js 文档是这样的:

var animation = anime({
  targets: '.play-pause-demo .el',
  translateX: 270,
  delay: function(el, i) { return i * 100; },
  direction: 'alternate',
  loop: true,
  autoplay: false,
  easing: 'easeInOutSine'
});

document.querySelector('.play-pause-demo .play').onclick = animation.play;
document.querySelector('.play-pause-demo .pause').onclick = animation.pause;

有谁知道如何使用一个类从多个元素运行相同的动画?谢谢!

【问题讨论】:

    标签: javascript anime.js


    【解决方案1】:

    我花了一些时间阅读文档,看来您必须使用循环遍历所有元素,并且需要附加 onclick 事件。

    这里是工作示例从多个元素运行相同的动画:

    var animation = anime({
                targets: '.play-pause-demo',
                translateX: 270,
                delay: function (el, i) { return i * 100; },
                direction: 'alternate',
                loop: true,
                autoplay: false,
                easing: 'easeInOutSine'
            });
    
    
    document.querySelectorAll(".correct").forEach((el)=> el.onclick = animation.play);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" ></script>
    
        <button class="correct">btn 1</button>
        <button class="correct">btn 2</button>
        <button class="correct">btn 3</button>
        <button class="correct">btn 4</button>
        <button class="correct">btn 5</button>
    
        <div class="play-pause-demo">this is div</div>

    【讨论】:

    • 感谢 Alireza 的回复,但我的问题是指触发动画的元素而不是目标 (document.querySelector('.play-pause-demo .play').onclick = animation.玩;)
    • Tahnks 再次 Alireza - 我明白你的意思,但不幸的是它不起作用。我还尝试将此“animation.play”应用于通过“getElementById”定位的特定元素,但它也不起作用。它仅在我使用 querySelector 方法时才有效 - 因此我认为这是一个anime.js 问题
    • 我更新了我的答案,我把我的代码作为sn-p给你请再检查一遍。
    • 谢谢它有效! - 我想我没有正确编写循环
    猜你喜欢
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 2021-04-17
    • 2023-04-04
    • 2020-09-22
    相关资源
    最近更新 更多