简体   繁体   中英

CSS Animation using Jquery and '.css'

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

The code

  $(".container>parent").click(function () {
    $('.element').css({
      'animation': 'fadeInUp .2s',
      '-webkit-animation': 'fadeInUp .2s'
    });
  });

The problem

Animation runs, but only one time. 'Infinite' attribute causes chaos :P

What else could I do, to play that animation every single time someone click it?

Thanks for your time.

My HTML :

            <span class="parent">
                <img src="assets/myimage.png" class="filter-image">
                <span class="element">Text</span>
            </span>  

I want to animate the text everytime I click it.

$(".container>parent").click(function() {
    $('.element').css({
        'animation': 'fadeInUp .2s',
        '-webkit-animation': 'fadeInUp .2s'
    });

    setTimeout(function(){
        $('.element').removeAttr('style');
    },300);
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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