Jquery fadeOut / fadeIn回调无法正常工作

我建立一个小脚本动画列表。 这是我的html结构:

  • Item-1
  • Item-2
  • Item-3
  • ...
  • Item-13
  • Item-14
  • Item-15

我一次只显示四个li,“下一个”按钮淡出显示的四个淡出淡出淡出接下来的四个。 但是这些趋势同时适用于两者。 我试图在第一次淡入淡出时使用回调函数,但我无法使其工作。

这是脚本:

 $('li:gt(3)').css('display', 'none'); //Define the interval of li to display var start = 0; var end = 4; //Get the ul length var listlength = $("li").length; $("button").click(function() { // FadeOut the four displayed li $('ul li').slice(start,end).fadeOut(500, function(){ // Define the next interval of four li to show start = start+4; end = end+4; // Test to detect the end of list and reset next interval if( start > listlength ){ start = 0; end = 4; } //Display the new interval $('ul li').slice(start,end).fadeIn(500); }); }); 

有什么线索吗?

问题是每个动画元素调用一次.fadeOut()回调,而不是一次。 你可以修改你的代码以保持计数被调用的次数,但是更容易 – 假设至少jQuery 1.6 – 是使用.promise(),它将在所有相关动画完成后解析:

 $(document).ready(function() { var $lis = $("li.slider"), start = 0; $lis.hide().slice(start, start+4).show(); $("button").click(function() { $lis.slice(start, start+4) .fadeOut(500) .promise() .done(function() { start += 4; if (start > $lis.length) start = 0; $lis.slice(start, start+4).fadeIn(); }); }); }); 

演示: http : //jsfiddle.net/w7Yuk

我对您的代码进行了其他一些更改,例如,使用li元素缓存jQuery对象,并删除“end”变量。

我创建了一个很好的小jsFiddle演示 ,它可以修改你所拥有的并为你提供一个很好的平滑过渡:

HTML:

给按钮一个“下一个”的ID,以便您可以专门定位它,以防页面上有其他按钮。

 
  • Item-1
  • Item-2
  • Item-3
  • Item-4
  • Item-5
  • Item-6
  • Item-7
  • Item-8
  • Item-9
  • Item-10
  • Item-11
  • Item-12
  • Item-13
  • Item-14
  • Item-15
  • Item-16

CSS:

从显示无启动开始,所以我们可以在加载时很好地淡化它们。

 .slider { display: none; } #next { display: none; } 

jQuery的:

我喜欢缓存元素,所以我开始这样做。 然后我淡出前4个LI元素和下一个按钮。 我使用推荐的.on()处理程序来绑定下一个按钮的click事件。 在我们设置startend之后,我们在下一个按钮和当前的4个LI元素上调用.fadeOut() 。 现在,你的回调是棘手的原因是因为它们是你选择器中每个元素的回调(所以4次)。 相反,我们需要使用.promise()等待所有这些作为一个整体完成,然后我们可以在下一个按钮和下一个4 LI元素上调用.fadeIn()方法。 只是旁注,我使用.stop(true,true)来消除可能存在的任何动画排队。

 var $list = $("ul li"); var $next = $("#next"); var start = 0; var end = 4; $next.fadeIn(500); $list.slice(start,end).fadeIn(500); $next.on("click", function() { start += 4; end += 4; if( start >= $list.length ){ start = 0; end = 4; } $next.stop(true,true).fadeOut(500); $list.stop(true,true).fadeOut(500); $list.promise().done(function() { $list.slice(start,end).stop(true,true).fadeIn(500); $next.stop(true,true).fadeIn(500); }); });