繁体   English   中英

如何使jQuery每个循环重复无数次

[英]How to make jQuery each loop repeat infinite number of times

我正在尝试创建幻灯片并在循环遍历每个图像后重复each循环。 我已经尝试了所有方法,但是在循环遍历每个图像后无法使循环继续。 请在下面查看我的代码并尝试。

有人有想法么? 已经尝试了一切。

html

<img src="http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-1.jpg" />
<img src="http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-5.jpg" />
<img src="http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-3.jpg" />

js

function test() {
    $("img").each(function(index) {
        $(this).hide();
        $(this).delay(3000 * index).fadeIn(3000).fadeOut();
    });

   if(index === 3){
      index = 0;
   }
}
test();

您应该只是在间隔之后再次开始循环,而无需重置索引(这也完全不起作用)。

function test() {
    $("img").each(function(index) {
        $(this).hide();
        $(this).delay(3000 * index).fadeIn(3000).fadeOut();
    });
    setTimeout(test,9400)
}
test();

由于存在三张img,每张img的延迟时间为3000,默认情况下,fadeOut需要400毫秒,因此延迟时间应为:

3 * 3000 + 400 = 9400

请注意,每个下一个fadeIn都不会等待上一个fadeOut的完成,因此会窃取fadeOut的前两个400 ms延迟。

最好的选择是兑现承诺:

function test() {
    $("img").hide().each(function(index) {
        $(this).delay(3000 * index).fadeIn(3000).fadeOut();
    }).promise().done(test);
}
test();

-jsFiddle-

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM