如何在点击时在 javascript 中重新激活?

How to reanimate in javascript on click?

我在 css 中使用关键帧创建了动画,如何重新使用该动画 onclick? 我必须在点击时更改 header 的背景,例如旋转木马,并且 header 必须在每次点击时设置动画。但它不起作用。我将 header.style.animation 设置为 null 并在每次点击时重写 header.style.animation = 'animate-bg 1s linear',仍然无法正常工作

请先在您的问题中添加您的代码。

然后添加一个class“active”onclick按钮

button.active header{
  animation: animate-bg 1s linear;
}

让我们将您的动画添加到 class,您只需删除并再次添加 class 即可触发动画。 此解决方案使用 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>