问题描述
我已经使用CSS中的关键帧创建了动画,如何在onclick上重新使用该动画? 我必须更改点击标题的背景,例如轮播,并且每次点击都必须对标题进行动画处理。但这是行不通的。我将header.style.animation设置为null,并在每次点击中重写header.style.animation ='animate-bg 1s linear',仍然无法正常工作
解决方法
请首先在您的问题中添加代码。
在按钮上添加“ 活动”类别,然后
button.active header{
animation: animate-bg 1s linear;
}
,
让我们将动画添加到类中,您只需删除并再次添加类即可触发动画。
此解决方案使用setTimout
确保浏览器呈现删除操作。
document.getElementById("header").addEventListener("click",function(e){
e.target.classList.remove("anim");
setTimeout(function(){
e.target.classList.add("anim");
});
})
@keyframes animate-bg {
0% {background-color: red;}
25% {background-color: yellow;}
50% {background-color: blue;}
100% {background-color: green;}
}
.anim {
animation: animate-bg 2s linear;
}
<div id="header">Hello Header</div>