Jqueryeach,如何在完成后重新循环
题
我有这段代码来运行幻灯片(这只是我的代码中真正发生的事情的一部分)
var slideshow = {
delay: 5000,
actions:[],
run: function() {
if (slideshow.actions.length) {
slideshow.actions.shift()();
setTimeout(slideshow.run, slideshow.delay);
}
}
};
var tn;
$(".sideimg").each(function(){
var that = this;
slideshow.actions.push(function(){
if (tn != "") {
out(tn);
}
over($(that).attr("id"));
var $paneTarget = $('#lyr1');
var $target = $paneTarget.find('#'+$(that).attr("id"));
$paneTarget.stop().scrollTo( $target , 800 );
$("#rimg").fadeOut("slow",function () {
$("#rimg").attr("src",$(that).attr("bsrc"));
$("#rimg").attr("alt",$(that).attr("alt"));
$("#rimg").fadeIn("normal");
});
tn = $(that).attr("id");
});
});
运行完每个 sideimg 类后,它会停止......我需要从头开始...我试图回忆起来 - 但什么也没发生
多谢你们
解决方案
对于这种情况,我根本不会使用each 方法。我将使用 setTimeout,一个包含图像/href 信息的对象数组,以及一个告诉您在图像数组中的位置的值。当到达数组末尾时,重置值(为了清晰起见,对以下代码进行了简化,未进行测试):
var index = 0;
var images = // array of image containing objects here.
function RunSlideShow()
{
// modify the following line to perform any effects, etc, and other attribute settings you need.
$("#rimg").attr("src", images[index].image);
index = index + 1;
if (index = images.length)
index = 0;
window.setTimeout('RunSlideShow();', 5000);
}
RunSlideShow();
每次调用幻灯片对象中的函数时,您确实需要 该功能 在退出之前加载下一张幻灯片。每次重新循环完成后的问题是:“什么时候停止?”如果预先加载所有图像,要永远继续,您将导致无限的循环,并且很可能会崩溃浏览器。您需要相同的函数来设置图像,然后准备要显示的下一个图像,但它看起来应该不会比下一个图像更远。任何时候你试图超越这一点,你都面临着创建一个永远不会停止的不断增长的项目集合的风险。
其他提示
在运行方法中,您可以移动数组元素。这将它们从数组中移除。.您应该移动它,然后将其推回末端...
var slideshow = {
delay: 5000,
actions: [],
timer: null,
pause: function(){ clearTimeout( slideshow.timer ); },
resume: function(){ slideshow.timer = setTimeout(slideshow.run, slideshow.delay); },
run: function() {
if (slideshow.actions.length) {
var current = slideshow.actions.shift();
current();
slideshow.actions.push( current );
slideshow.timer = setTimeout(slideshow.run, slideshow.delay);
}
}
};
我刚刚添加了将保存超时对象的计时器变量,以便您可以按需清除它,还可以使用几种启动/停止幻灯片的方法。
现在只需将悬停事件添加到您要启动/停止幻灯片的元素中slideshow.pause()
或者 slideshow.resume()
不隶属于 StackOverflow