【问题标题】:How to reanimate in javascript on click?如何在点击时在javascript中重新激活?
【发布时间】:2020-08-18 08:13:14
【问题描述】:

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

【问题讨论】:

标签: javascript css animation resultset solver


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    然后添加一个类“active”点击按钮

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

    【讨论】:

    • 使用 flag 选项标记问题以关闭并就如何改进问题发表评论。
    猜你喜欢
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多