使用Javascript和CSS在事件触发器上制作动画

时间:2017-05-25 08:57:50

标签: javascript jquery html css animation

我是新手使用javascript和CSS,目前我正在尝试制作一个在事件调用时触发的小动画。动画很简单,只会改变图像的透明度。我的问题是动画只在调用函数的每个时间都有效。

一个名为" pulse()"的函数每当我想要动画发生时调用。

 <script>
    function pulse() {
      $('.transform').toggleClass('transform-active');
    }
 </script>

CSS看起来像这样:

.lock-image {

}

.transform {
  -webkit-transition: all 1s ease-in-out;  
  -moz-transition: all 1s ease-in-out;  
  -o-transition: all 1s ease-in-out;  
  -ms-transition: all 1s ease-in-out;  
  transition: all 1s ease-in-out;
}

.transform-active {
  /*animation-delay: 2s;*/
  animation-iteration-count: 1;
  animation: pulse 0.5s;
  animation-direction: alternate;
}


@keyframes pulse {
  0% {
    opacity: 1;
  }
  50%{
    opacity: 0.3;
  }
  100% {
    opacity: 1;
  }
}

完成动画的图像是这样完成的;

  <div class="lock-image transform">
    <img id="myImage" src="pic_locked.png" class="img-responsive " style="display:inline" alt="Lock" width="100" height="80">
  </div>

如何更改代码,以便每次调用函数pulse()时动画都会发生?

1 个答案:

答案 0 :(得分:3)

您可以添加一个事件处理程序,以便在动画结束时删除该类。出于示例的目的,我已将图像更改为红色div

&#13;
&#13;
function pulse() {
  $('.transform').addClass('transform-active');
}

$('.transform').on('webkitAnimationEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function() {
  $(this).removeClass('transform-active');
})
&#13;
#myImage {
  display: block;
  background-color: red;
  width: 100px;
  height: 80px;
}

.transform {
  -webkit-transition: all 1s ease-in-out;
  -moz-transition: all 1s ease-in-out;
  -o-transition: all 1s ease-in-out;
  -ms-transition: all 1s ease-in-out;
  transition: all 1s ease-in-out;
}

.transform-active {
  /*animation-delay: 2s;*/
  animation-iteration-count: 1;
  animation: pulse 0.5s;
  animation-direction: alternate;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.3;
  }
  100% {
    opacity: 1;
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="lock-image transform">
  <div id="myImage"></div>
</div>
<br/>
<button type="button" onclick="pulse()">Pulse</button>
&#13;
&#13;
&#13;