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

◇◆丶佛笑我妖孽 提交于 2020-01-17 09:19:48

问题


I have a problem. Im using Bounce.js to create nice menu animations (with some cool effects). Bounce.js using css keyframes animations which can be problematic to restart. I got menu and when I click a button and when .show class is added it should fire show animation. But when I press that button again hide class should be added with hide animation (which is just reverse version of previous animation).

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).


回答1:


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):

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:

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/

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



来源:https://stackoverflow.com/questions/38049270/css3-keyframes-animation-on-click-with-addclass-how-to-restart-css3-animation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!