Jquery fadeOut / fadeIn回调不工作 [英] Jquery fadeOut/fadeIn callback not working
问题描述
我建立一个小脚本来动画列表。这是我的html结构:
i m building a little script to animate a list. Here is my html structure:
<ul>
<li class="slider"> Item-1 </li>
<li class="slider"> Item-2 </li>
<li class="slider"> Item-3 </li>
...
<li class="slider"> Item-13 </li>
<li class="slider"> Item-14 </li>
<li class="slider"> Item-15 </li>
</ul>
<button> Next </button>
我一次只显示四个li,下一个按钮fadeOut显示四个li在接下来的四个。但是衰落正在一起应用。我试图在第一次褪色时使用回调函数,但我不能让它工作。
I'm displaying only four li at one time, the "next" button fadeOut the displayed four li et fadeIn the next four ones. But the fades are applying both together. I've tried to use callback function on the first fade but i can't make it work.
这里是脚本:
$('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(),将在所有相关的动画完成后解决:
The problem is that the .fadeOut() callback is called once per animated element, not once at the end. You could modify your code to keep a counter of how many times it has been called, but far easier - assuming at least jQuery 1.6 - is to use .promise(), which will resolve after all the associated animations complete:
$(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();
});
});
});
我对你的代码做了一些其他的更改,例如,用li元素缓存jQuery对象, end变量。
I made a couple of other changes to your code, e.g., caching the jQuery object with the li elements, and removing the "end" variable.
这篇关于Jquery fadeOut / fadeIn回调不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!