您需要考虑您的代码应该做什么,而不是用户做什么来触发您的代码。因此,您只希望代码自动显示下一张图片,而不是“自动‘点击’”。
所以第一步是将你的代码移出click处理程序:
function showImage(img){
$('div.feature-photo img').hide().attr('src',$(img).attr('src')).fadeIn();
}
$('#thumbs img').click(function() {
showImage(this);
});
然后问题就变成了:如何使用“下一个”图像每五秒调用一次showImage。好吧,首先我们要记住“当前”图像是什么。很容易修改我们的showImage 来做到这一点:
var current = null;
function showImage(img){
current = img;
$('div.feature-photo img').hide().attr('src',$(img).attr('src')).fadeIn();
}
那么我们只需要在 5 秒内触发即可。您可以使用setInterval,但我发现它很容易失控,因此我使用setTimeout 的一系列链接,每个都设置下一个。什么是一个很好的触发器?好吧,在用户点击图片五秒后,可能就在showImage:
var current = null;
var timer = 0;
function showImage(img){
current = img;
$('div.feature-photo img').hide().attr('src',$(img).attr('src')).fadeIn();
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(nextImage, 5000);
}
好的,那么nextImage 应该是什么样子?我想说我们可能想使用current,也许:
function nextImage() {
var $current;
if (timer) {
clearTimeout(timer);
timer = 0;
}
if (current) {
$current = $(current);
next = $current.nextAll("img")[0];
if (!next) {
$current.siblings("img")[0];
}
if (next) {
showImage(next);
}
}
}
您可以通过显示第一张图片从一开始就开始:
showImage($("#thumbs img")[0]);
因此,将所有这些放在一起,并确保我们将其包装在一个作用域函数中,这样我们就不会创建全局符号:
(function() {
var current = null;
var timer = 0;
function showImage(img){
current = img;
$('div.feature-photo img').hide().attr('src',$(img).attr('src')).fadeIn();
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(nextImage, 5000);
}
function nextImage() {
var $current;
if (timer) {
clearTimeout(timer);
timer = 0;
}
if (current) {
$current = $(current);
next = $current.nextAll("img")[0];
if (!next) {
$current.siblings("img")[0];
}
if (next) {
showImage(next);
}
}
}
$('#thumbs img').click(function() {
showImage(this);
});
showImage($("#thumbs img")[0]);
})();
(或者,您可以使用 jQuery ready 来代替普通的作用域函数。)
以上内容相当粗略,完全未经测试,但你明白了。