简体   繁体   English

单击CSS3关键帧动画(带有addClass)。 如何通过添加CSS类重新启动CSS3动画?

[英]CSS3 keyframes animation on click (with addClass). How to restart CSS3 animation with adding css class?

I have a problem. 我有个问题。 Im using Bounce.js to create nice menu animations (with some cool effects). 我使用Bounce.js创建漂亮的菜单动画(具有一些很酷的效果)。 Bounce.js using css keyframes animations which can be problematic to restart. 使用css关键帧动画的Bounce.js可能会重新启动会出现问题。 I got menu and when I click a button and when .show class is added it should fire show animation. 我有菜单,当我单击按钮时,当添加.show类时,它将触发显示动画。 But when I press that button again hide class should be added with hide animation (which is just reverse version of previous animation). 但是,当我再次按下该按钮时,应在hide类中添加hide动画(这是先前动画的反向版本)。

Js is working (classes are adding and removing properly) but animation is fired only once - and there is no hiding animation (menu element just disappears with out animating it self). Js正在工作(类正在正确添加和删除),但是动画仅触发一次-并且没有隐藏的动画(菜单元素只是消失而没有对其自身进行动画处理)。

You can do it in a serval ways. 您可以通过服务方式做到这一点。

One way is to trigger re-flow of the element before adding animation class to it. 一种方法是在将动画类添加到元素之前触发元素的重排。

element.offsetWidth = element.offsetWidth;

For example (vanilla JS): 例如(香草JS):

if (element2.classList.contains('show')) {
      element2.classList.remove("show");
      //restarting css3 keyframe animation
      **element2.offsetWidth = element2.offsetWidth;**
      element2.classList.add("hide");
  }else{
        element2.classList.remove("hide");
      //restarting css3 keyframe animation
      **element2.offsetWidth = element2.offsetWidth;**
      element2.classList.add("show");
  }

jQuery version: jQuery版本:

if(settingPopup.hasClass('show')){
        settingPopup.removeClass('show');
      //line below is a fix to restart css3 keyframe animation
      //settingPopup.outerWidth(settingPopup.outerWidth)
      settingPopup.outerWidth(settingPopup.outerWidth).addClass('hide');
  }else{
        settingPopup.removeClass('hide');
      //line below is a fix to restart css3 keyframe animation
      //settingPopup.outerWidth(settingPopup.outerWidth)
      settingPopup.outerWidth(settingPopup.outerWidth).addClass('show');
  }

And here is working fiddle for it: https://jsfiddle.net/zpawpvke/2/ 这是为此工作的小提琴: https : //jsfiddle.net/zpawpvke/2/

Based on: https://css-tricks.com/restart-css-animation/ 基于: https : //css-tricks.com/restart-css-animation/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM