[英]How can I get a JavaScript CSS animation to run more than one time?
我有一些运行 CSS animation 的 JavaScript 代码。它工作正常,但我需要刷新浏览器才能让它再次运行。 如何修改我的代码以使其在每次单击按钮时运行?
下面是我使用的代码。
document.getElementById('LogoContainer').addEventListener('click',function() {
var c = document.getElementsByClassName('logo-rec');
for (var i = 0; i < c.length; i++) {
c[i].classList.add('logo-animate');
}
})
<button id="LogoContainer">
<div class="logo-rec"></div>
</button>
CSS
.logo-animate {
animation-name: MoveLeft;
animation-duration: 3s;
}
@keyframes MoveLeft {
0% { transform: translatex(0px) }
50% { transform: translatex(-15px) }
100% { transform: translatex(35px) }
}
问题是,一旦 animation 运行,系统就会认为 - 我已经运行了它,所以当您单击它时它不会再次运行(animation 名称保持不变)。
因此,此代码段为 animationend 事件添加了一个事件侦听器,当发生这种情况时,它会删除导致 animation 的 class 设置,因此当您再次单击时,它是一个新的 class 设置,并且 animation 会再次发生。
document.getElementById('LogoContainer').addEventListener('click', function() { var c = document.getElementsByClassName('logo-rec'); for (var i = 0; i < c.length; i++) { c[i].classList.add('logo-animate'); c[i].addEventListener('animationend', function() { this.classList.remove('logo-animate'); }); } })
.logo-animate { animation-name: MoveLeft; animation-duration: 3s; } @keyframes MoveLeft { 0% { transform: translatex(0px) } 50% { transform: translatex(-15px) } 100% { transform: translatex(35px) } }
<button id="LogoContainer"> <div class="logo-rec">abcd</div> </button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.