这是我们使用的幻灯片:
http://www.littlewebthings.com/projects/blinds/
这是 JS 文件:
http://www.littlewebthings.com/projects/blinds/js/jquery.blinds-0.9.js
但是,此幻灯片放映没有自动浏览每张图片的设置。您仍然必须单击其下方的数字才能查看图像。有人知道要在 javascript 代码中添加什么以使其自动遍历每个图像吗?
谢谢!
最佳答案
此解决方案使用闭包和递归。
var SlideChanger = function(seconds_each) {
var index = -1;
// on the first cycle, index will be set to zero below
var maxindex = ($(".change_link").length) - 1;
// how many total slides are there (count the slide buttons)
var timer = function() {
// this is the function returned by SlideChanger
var logic = function() {
// this is an inner function which uses the
// enclosed values (index and maxindex) to cycle through the slides
if (index == maxindex)
index = 0; // reset to first slide
else
index++; // goto next slide, set index to zero on first cycle
$('.slideshow').blinds_change(index); // this is what changes the slide
setTimeout(logic, 1000 * seconds_each);
// schedule ourself to run in the future
}
logic(); // get the ball rolling
}
return timer; // give caller the function
}
SlideChanger(5)(); // get the function at five seconds per slide and run it
我们在这里所做的是在定义它的函数 (SlideChanger
) 之外公开内部函数 timer
。此函数 (timer
) 可以访问 SlideChanger
中定义的变量(index
和 maxindex
)。
现在我们已经在封闭环境中设置了变量和返回调用者的函数,我们可以在logic
中设置逻辑引擎。当 logic
运行时,它使用 index
和 maxindex
来确定接下来应该显示哪张幻灯片,显示幻灯片,并安排自己运行以后再来。
调用时,返回函数会调用逻辑
来启动程序。然后 logic
每次运行时都会安排自己在未来运行,从而无限期地重复。
因此,总而言之,我们使用数字参数 x
调用 SlideChanger
。它返回一个函数,该函数在被调用后将每 x
秒更改一次幻灯片。
同样概念的另一种写法。
(function(seconds_each) {
var index = -1;
// on the first cycle, index will be set to zero below
var maxindex = ($(".change_link").length) - 1;
// how many total slides are there (count the slide buttons)
return function() {
// this is the function returned by SlideChanger
var logic = function() {
// this is an inner function which uses the
// enclosed values (index and maxindex) to cycle through the slides
if (index == maxindex)
index = 0; // reset to first slide
else
index++; // goto next slide, set index to zero on first cycle
$('.slideshow').blinds_change(index); // this is what changes the slide
setTimeout(logic, 1000 * seconds_each);
// schedule ourself to run in the future
}
logic(); // get the ball rolling
}
})(5)(); // get the function at five seconds per slide and run it
JavaScript 是一种很好的语言,具有许多函数式编程结构,例如高阶函数(创建函数或接受函数作为参数的函数)和匿名函数。有关详细信息,请参阅 http://www.ibm.com/developerworks/web/library/wa-javascript.html
关于javascript - 有没有办法让这个幻灯片自动移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4273617/