Possible to reverse a css animation on class removal?

前端 未结 6 1045
傲寒
傲寒 2021-02-02 05:03

Essentially what I\'m trying to do is give an element a CSS animation when it gains a class, then reverse that animation when I remove the class without playing the anim

6条回答
  •  情书的邮戳
    2021-02-02 05:53

    You can make use of the attribute animation-direction to run the same animation in reverse. If you couple this with one of the many methods described here for restarting an animation- we can start the animation forwards on mouseenter, then on mouseleave we can restart it and play it in reverse.

    I don't know how to use jQuery very well, so I chose one of the non-jQuery methods mentioned in the article.

    const element_button = document.getElementById('trigger');
    const element_item = document.getElementById('item');
    
    element_button.addEventListener("mouseenter", () => {
      if (element_item.classList.contains('animate-backwards')) {
        element_item.classList.remove('animate-backwards');
        void element_item.offsetWidth;
      }
      
      element_item.classList.add('animate-forwards');
    });
    
    element_button.addEventListener("mouseleave", () => {
      element_item.classList.remove('animate-forwards');
      void element_item.offsetWidth;
      
      element_item.classList.add('animate-backwards');
    });
    

    and

    #item.animate-forwards {
      animation: flipper 0.7s normal;
      -webkit-animation: flipper 0.7s normal;
      
      animation-fill-mode: forwards;
      -webkit-animation-fill-mode: forwards;
    }
    
    #item.animate-backwards {
      animation: flipper 0.7s reverse;
      -webkit-animation: flipper 0.7s reverse;
      
      animation-fill-mode: forwards;
      -webkit-animation-fill-mode: forwards;
    }
    

    Here is a jsFiddle for the above code.

提交回复
热议问题