我正在构建一个小脚本来动画列表。这是我的 html 结构:
<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: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();
});
});
});
Demo: http://jsfiddle.net/w7Yuk http://jsfiddle.net/w7Yuk
我对代码进行了一些其他更改,例如,使用 li 元素缓存 jQuery 对象,并删除“end”变量。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)