Can jquery animations be chained programmatically?

前端 未结 4 1336
走了就别回头了
走了就别回头了 2021-01-24 20:46

I have this code:

jQuery(\'#flash\').animate({opacity: 0.35}, 200)
                .animate({opacity: 0}, 200)
                .animate({opacity: 0.35}, 200)
            


        
相关标签:
4条回答
  • 2021-01-24 21:18

    You can chain the animation using a loop if that's what you're looking for.

    var $flash = jQuery('#flash'), i;
    
    for (i = 0; i < 10; i++) {
        $flash = $flash.animate({opacity: 0.35}, 200)
                       .animate({opacity: 0}, 200);
    }
    
    0 讨论(0)
  • 2021-01-24 21:19

    No, you can't chain animations without editing the animation queue. If you want to chain a variable, but limited number of times you can do easily with a loop:

    var flash = $("#flash");
    for (var i=0; i<n; i++)
        flash.animate({opacity: 0.35}, 200).animate({opacity: 0}, 200);
    

    If you want an endless loop, or one that stops when a condition is to be fulfilled in the future, you want to hook a callback on the animation queue, restarting the function:

    var flash = $("#flash");
    function anim() {
        // if (condition)
        flash.animate({opacity: 0.35}, 200).animate({opacity: 0}, 200, anim);
                                                // call "recursively": ^^^^
    }
    anim();
    
    0 讨论(0)
  • 2021-01-24 21:19

    If I understand correctly you only need a FOR loop:

    function animate_n_times(n) {
       var flash = $('#flash');
       for(var i=0;i<n;i++) {
          flash.animate({opacity: 0.35}, 200)
               .animate({opacity: 0}, 200);
       }
    
    }
    

    then called like:

    animate_n_times(3);
    
    0 讨论(0)
  • 2021-01-24 21:27

    There is a shorter alternative, using the extension jquery-timing:

    Animate a given number of times:

    $('#flash').repeat().animate({opacity:0.35}, 200)
        .animate({opacity:0}, 200).until(10);
    

    As endless loop:

    $('#flash').repeat().animate({opacity:0.35},200).animate({opacity:0},200,$);
    

    For details see the API of .repeat(), .until(count), and .animate(…,$).

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