是否有可行的方法来使用JS触发CSS关键帧动画? [英] Is there a feasible way to trigger CSS keyframe animation using JS?

查看:614
本文介绍了是否有可行的方法来使用JS触发CSS关键帧动画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自然地,我们可以使用关键帧创建CSS动画,并从那里对其进行控制.

Naturally, we can create a CSS animation using keyframes, and control it from there.

但是,理想情况下,我希望通过单击按钮来触发此动画-因此单击按钮将是一个事件...

However, ideally, I would like to trigger this animation from a button click - so the button click would be an event...

@keyframes fade-in {
    0% {opacity: 0;}
    100% {opacity: 1;}
}

现在,在单击时,我要触发此动画;而不是在CSS动画属性中.

Now, on click, I want to trigger this animation; as opposed to from within the CSS animation property.

推荐答案

请参见此处 jsfiddle

see here jsfiddle

如果您希望每次按下按钮时动画都能正常工作,请使用以下代码:

if you want your animation to work every time you press the button use this code :

$('button').click(function() {
    $(".fademe").addClass('animated');
    setTimeout(function() {
      $(".fademe").removeClass('animated');
    }, 1500);
});

,在这种情况下,1500animation-duration1.5s

where 1500 is the animation-duration in this case, 1.5s

$('button').click(function() {
  $(".fademe").addClass('animated');
  setTimeout(function() {
    $(".fademe").removeClass('animated');
  }, 1500);
});

.fademe {
  width: 100px;
  height: 100px;
  background: red;
}

.fademe.animated {
  animation: fade-in 1.5s ease;
}


@keyframes fade-in {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fademe">

</div>

<button>CLICK ME</button>

解释:

  1. 在按钮上单击,将类animated(或任何其他类)添加到要向其应用动画的元素上,.fademe
  2. 制作setTimeout(function()removeClass延迟动画1.5s1500ms
  3. 的持续时间
  4. 在CSS中编写动画的声明@keyframes,然后将其添加到具有JQ .fademe.animated
  5. 添加的类的元素中
  1. on click on the button add class animated ( or any other class ) to the element you want to apply the animation to , .fademe
  2. make a setTimeout(function() to delay the removeClass for the duration of the animation 1.5s or 1500ms
  3. write in CSS the declaration of the animation , @keyframes, and add it to the element with the class added by the JQ .fademe.animated

这篇关于是否有可行的方法来使用JS触发CSS关键帧动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆