CSS Animation using Jquery and '.css'

前端 未结 2 1725
没有蜡笔的小新
没有蜡笔的小新 2021-01-24 05:58

So I have a piece of code. The purpose is to play a selected animation from Animate.css on click.

The code

  $(\".conta         


        
相关标签:
2条回答
  • 2021-01-24 06:12
    $(".container>parent").click(function() {
        $('.element').css({
            'animation': 'fadeInUp .2s',
            '-webkit-animation': 'fadeInUp .2s'
        });
    
        setTimeout(function(){
            $('.element').removeAttr('style');
        },300);
    });
    
    0 讨论(0)
  • 2021-01-24 06:32

    The animation won't work the second time if you don't remove animation class after the current animation finishes.

    But how to remove animation property after the animation finishes?

    Here's a snippet:

    var support = {};
    support.animation = (function() {
        var animationEnd = (function() {
            var element = document.body || document.documentElement,
                animEndEventNames = {
                    WebkitAnimation : 'webkitAnimationEnd',
                    MozAnimation    : 'animationend',
                    OAnimation      : 'oAnimationEnd oanimationend',
                    animation       : 'animationend'
                }, name;
    
            for (name in animEndEventNames) {
                if (element.style[name] !== undefined) return animEndEventNames[name];
            }
        }());
    
        return animationEnd ? { end: animationEnd } : false;
    })();
    
    
    
    function animate(elem, cls, callback) {
        var $elem = $(elem);
    
        var onEndCallbackFn = function(ev) {
            if (support.animation) {
                $elem.removeClass(cls);
                this.removeEventListener(support.animation.end, onEndCallbackFn);
            }
    
            if (callback && typeof callback === 'function') { callback.call(this, ev); }
        };
    
        if (support.animation) {
            $elem.addClass(cls);
            $elem[0].addEventListener(support.animation.end, onEndCallbackFn);
        } else {
            onEndCallbackFn();
        }
    }
    

    usage is simple, just call animate function, like this:

    animate($('.selector'), 'classWithAnimation', callbackFn);
    

    In you case, you said you are using animate.css library:

    $(".container>parent").click(function() {
        animate($('.element'), 'animated fadeInUp', function() {
            console.log('animation complete');
        );
    });
    

    Live example: jsFiddle

    0 讨论(0)
提交回复
热议问题