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

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

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

     #tml-container p { display: none; }    

Testimonial 1

Testimonial 2

Testimonial 3

$(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(); });

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

 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


可重用的插件版本:

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

 (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)); 

可用作:

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

DEMO

更改了自行开发的插件以满足您的要求,但没有完全测试它。

至少应该告诉你如何正确设置这样的东西。

希望这可以帮助 :)

 (function($){ $(function(){ $('#tml-container').testimonialFader(); }); $.fn.testimonialFader = function(){ return this.each(function(){ var $par = $(this), $testimonials = $par.children('p'), $current = $testimonials.first(); $testimonials.not(':first').hide(); $testimonials.on('testimonialReady.testimonialFader', wait); $testimonials.on('waitComplete.testimonialFader', showNext); $current.trigger('testimonialReady.testimonialFader'); function wait(e){ $current.trigger('waitStart.testimonialFader'); setTimeout( function(){ $current.trigger('waitComplete.testimonialFader'); }, 6000 ); } function showNext(){ $current.trigger('testimonialChange.testimonialFader'); if($testimonials.length > 1){ var $next = $current.next(); if($next.length == 0){ $next = $testimonials.first(); } $current.fadeOut(800); $next.fadeIn(800, function(){ $next.trigger('testimonialReady.testimonialFader'); } ); $current = $next; } } }); }; }(jQuery));