之前可能已经回答了这个问题,我已经知道这应该如何工作,但由于某种原因,它不是。我认为这可能是我如何循环元素。
$(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();
});
});
然后列表是这样的:
<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>
我试图让它逐个循环遍历元素,经过一段时间后,列表项调用函数并隐藏自身,然后计数器递增,然后显示当前索引。 我怀疑罪魁祸首是这个,好像我在它所调用的函数中放了一个警告:
$(element + ' li:eq(' + idx + ')').fadeOut();
答案 0 :(得分:5)
主要问题是,正如评论所述,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);
我们尽量不使用动态生成的选择器来唤起jQuery函数,而是操纵包含在开始时缓存的所有幻灯片的jQuery对象的单个实例。我们还使用fade
函数提供的回调函数,在当前幻灯片淡出后淡入下一张幻灯片。
有关简单演示的信息,请参阅http://www.jsfiddle.net/b3Lf5/1/
答案 1 :(得分:2)
我会这样做:
$(document).ready(function() {
var element = '#gallery ul#gallery-container';
var idx = 0;
var timeout = 3000;
var number = $(element + ' li').length;
setInterval(function () {
idx = (idx + 1) % number;
$(element + ' li:visible').fadeOut();
$(element + ' li:eq(' + idx + ')').fadeIn();
},timeout);
$(element + ' li:not(:first)').hide();
});
或者更好的是,将它包装在一个插件中:
(function ($) {
$.fn.customGallery = function (options) {
defaults = {
timeout : 3000
};
options = $.extend(defaults, options);
return this.each(function () {
var idx = 0, number = $(this).children('li').size(), element = this;
setInterval(function () {
idx = (idx + 1) % number;
$(element).children('li:visible').fadeOut();
$(element).children('li:eq(' + idx + ')').fadeIn();
},options.timeout);
$(element).children('li:not(:first)').hide();
});
};
}(jQuery));
jQuery(document).ready(function($) {
$('#gallery-container').customGallery()
});
编辑:编辑插件代码,使其符合良好做法。