如何在js中为点击事件添加多个时间动画css类?

时间:2018-04-19 02:49:09

标签: javascript css animation animate.css

当我点击正确动画的按钮框时。它只能按时工作,第二次不工作。我怎么能管理这个?所以当我点击按钮不是一次时,我想动画这个。

function myFunction() {
  document.getElementById("box").classList.add('animated', 'bounceIn');
}
#box {
  background: red;
  height: 60px;
  width: 60px;
  margin-bottom: 20px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css">
<div class="container">
  <div class="row">
    <div id="box"></div>
  </div>
</div>
<div class="container">
  <div class="row">
    <button class="btn btn-sm btn btn-primary" onclick="myFunction()">click to animate</button>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

动画完成后需要删除此类

&#13;
&#13;
function myFunction() {
    document.getElementById("box").classList.add('animated','bounceIn');
  setTimeout(function() {
    document.getElementById("box").classList.remove('animated','bounceIn');
  }, 100)
}
&#13;
#box{
  background: red;
  height:60px;
  width:60px;
  margin-bottom:20px;
}
&#13;
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css">
<div class="container">
  <div class="row">
    <div id="box"></div>
  </div>
</div>
<div class="container">
  <div class="row">
<button class="btn btn-sm btn btn-primary" onclick="myFunction()">click to animate</button>
  </div>
</div>
&#13;
&#13;
&#13;

https://codepen.io/anon/pen/QrwWMO

或者你可以使用纯CSS,不需要使用javascript

&#13;
&#13;
#box{
  background: red;
  height:60px;
  width:60px;
  margin-bottom:20px;
}

button:active + #box{
  -webkit-animation-duration: 1s;
    animation-duration: 1s;
    -webkit-animation-fill-mode: both;
    animation-fill-mode: both;
      animation-name: bounceIn;
      animation-duration: .75s;
}
&#13;
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css">
<div class="container">
  <div class="row">
<!--     <div id="box"></div> -->
  </div>
</div>
<div class="container">
  <div class="row">
<button class="btn btn-sm btn btn-primary" >click to animate</button>
    <div id="box"></div>
  </div>
</div>
&#13;
&#13;
&#13;