Possible to reverse a css animation on class removal?

前端 未结 6 1062
傲寒
傲寒 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:45

    In addition to the answers here, please cache your $(selector)

    So you pretty much do this var elements = $(selector); to cache.

    Why?! Because if you use the code in the answers on this page as is you will ask the DOM for that same element collection ($('#item')) each time. DOM reading is an expensive operation.

    For example, the accepted answer would look something like so:

    var item = $('#item');
    $('#trigger').on({
        mouseenter: function(){
            item.show();
            item.addClass('flipped');
        },
        mouseleave: function(){
            item.removeClass('flipped');
        }
    });
    

    Since I've written all this text, might as well answer your question using CSS transitions

    I know you asked for a CSS animations example, but for the animation you wanted to do (a card flipping open), it can be easily achieved using CSS transitions:

    #item {
      width: 70px;
      height: 70px;
      background-color: black;
      line-height: 1;
      color: white;
    }
    
    #item+div {
      width: 70px;
      height: 100px;
      background-color: blue;
      transform: perspective(250px) rotateX(-90deg);
      transform-origin: 50% 0%;
      transition: transform .25s ease-in-out
    }
    
    #item:hover+div {
      transform: perspective(250px) rotateX(0);
    }

提交回复
热议问题