jQuery在div中一次循环一个p标签的.fadeIn和.fadeOut

Jus*_*tin 3 jquery loops this next fadein

下面的代码成功地在一个推荐中淡出6秒,等待3秒,然后将其淡出并继续下一个.一旦达到第三个见证,它就会跳回到第一个.这正是我想要的,但在我的实际网站上,我有三个以上的推荐,并且将来可能会增加更多.每次添加新推荐书时,我都不想再返回并添加新功能.我尝试了一段时间,使用"this"和.next()使其工作但失败了.我希望有人可以通过循环它并使其移动到容器中的下一个p标签而不必每次调用新函数来提高效率.感谢任何帮助,谢谢.

注意:我知道有类似的问题,但没有一个是完全相同的,答案是低于标准.

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<style>
#tml-container p { display: none; }
</style>
</head>
<body>

<div id="tml-container">
    <p id="one">Testimonial 1</p>
    <p id="two">Testimonial 2</p>
    <p id="three">Testimonial 3</p>
</div>

<script>
$(document).ready(function() {
    function doFade() {
        $("#one").fadeIn(6000,function() {
            $("#one").fadeOut(6000).delay(3000);
            setTimeout(fadeTwo,6000);
        });
    }

    function fadeTwo() {
        $("#two").fadeIn(6000,function() {
            $("#two").fadeOut(6000).delay(3000);
            setTimeout(fadeThree,6000);
        });
    }

    function fadeThree() {
        $("#three").fadeIn(4000,function() {
            $("#three").fadeOut(6000).delay(3000);
            setTimeout(doFade,6000);
        });
    }
    doFade();
});
</script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 15

这是一个非常简单的解决方案:

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());
Run Code Online (Sandbox Code Playgroud)

DEMO


可重用的插件版本:

它不是迭代某个元素的子元素,而是遍历所选元素.

(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));
Run Code Online (Sandbox Code Playgroud)

适用于:

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

DEMO