jQuery looping .fadeIn and .fadeOut of p tags within div one at a time

前端 未结 2 1387
甜味超标
甜味超标 2021-01-06 14:37

The code below successfully fades in one testimonial for 6 seconds, waits 3 seconds, and then fades it out and moves on to the next. Once it reaches the third testimonial it

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-06 14:53

    This is a very simple solution:

    function fade($ele) {
        $ele.fadeIn(6000).delay(3000).fadeOut(6000, function() {
            var $next = $(this).next('p');
            // if there is a following `p` element, it is faded in
            // otherwise start from the beginning by taking
            // the parent's first child
            fade($next.length > 0 ? $next : $(this).parent().children().first());
       });
    };  
    
    fade($('#tml-container > p').first());
    

    DEMO


    Reusable plugin version:

    Instead of iterating over the children of a certain element, it iterates over the selected elements.

    (function($) {
        var default_config = {
            fadeIn: 3000,
            stay: 3000,
            fadeOut: 3000
        };
    
        function fade(index, $elements, config) {
            $elements.eq(index)
              .fadeIn(config.fadeIn)
              .delay(config.stay)
              .fadeOut(config.fadeOut, function() {
                  fade((index + 1) % $elements.length, $elements, config);
              });
        }
    
        $.fn.fadeLoop = function(config) {     
            fade(0, this, $.extend({}, default_config, config));
            return this;
        };
    
    }(jQuery));
    

    Usable as:

    $('#tml-container > p').fadeLoop({fadeIn: 6000, stay: 3000, fadeOut: 6000});
    

    DEMO

提交回复
热议问题