Des*_*023 0 html javascript jquery gallery html-lists
这可能已经得到了回答,我已经知道这应该如何工作,但由于某种原因,它不是.我想这可能是我如何循环元素.
$(document).ready(function() {
var element = '#gallery ul#gallery-container';
var idx=0;
var timeout = 3000;
var number = $(element + ' li').length;
function changeSlide() {
$(element + ' li:eq(' + idx + ')').fadeOut();
idx = idx + 1;
if (idx == number) {
idx=0;
}
$(element + ' li:eq(' + idx + ')').fadeIn().delay(timeout).delay(0, function() {
changeSlide();
});;
}
$(element + ' li').hide();
$(element + ' li:first').fadeIn().delay(timeout).delay(0, function() {
changeSlide();
});
});
Run Code Online (Sandbox Code Playgroud)
然后列表是这样的:
<div id="gallery">
<ul id="gallery-container">
<li><img src="media/images/screen-shot-02.jpg" width="173" height="258" alt=" "></li>
<li><img src="media/images/screen-shot-01.jpg" width="173" height="258" alt=" "></li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
我试图让它逐个循环遍历元素,经过一段时间后,列表项调用函数并隐藏自身,然后计数器递增,然后显示当前索引.我怀疑罪魁祸首就像我在它被调用的函数中发出一个警告:
$(element + ' li:eq(' + idx + ')').fadeOut();
Run Code Online (Sandbox Code Playgroud)
主要问题是,正如评论所述,delay并不是你认为它做的 - 你应该看看本机setTimeout功能.除此之外,还有多个地方可以提高效率.看看这个:
var element = $('#gallery-container li'),
length = element.length,
current = 0,
timeout = 3000;
function changeSlide() {
element.eq(current++).fadeOut(300, function(){
if(current === length){
current = 0;
}
element.eq(current).fadeIn(300);
});
setTimeout(changeSlide, timeout);
}
element.slice(1).hide();
setTimeout(changeSlide, timeout);
Run Code Online (Sandbox Code Playgroud)
我们尽量不使用动态生成的选择器来唤起jQuery函数,而是操纵包含在开始时缓存的所有幻灯片的jQuery对象的单个实例.我们还使用函数提供的回调函数fade在当前淡出函数淡出后淡入下一张幻灯片.
有关简单演示,请参见http://www.jsfiddle.net/b3Lf5/1/