问题描述
我正在尝试使用播放按钮调用 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,easing: 'easeInOutSine'
});
document.querySelector('.play-pause-demo .play').onclick = animation.play;
document.querySelector('.play-pause-demo .pause').onclick = animation.pause;
有谁知道如何使用一个类从多个元素运行相同的动画?谢谢!
解决方法
我花了一些时间阅读文档,看来您必须对所有元素使用循环,并且需要附加 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>