【问题标题】:How to make jQuery each loop repeat infinite number of times如何使jQuery每个循环重复无限次
【发布时间】:2016-07-24 16:05:20
【问题描述】:

我正在尝试创建幻灯片并在循环浏览每个图像后重复 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();

【问题讨论】:

标签: javascript jquery


【解决方案1】:

您应该在间隔后再次启动循环,无需重置索引(这也完全没有任何作用)。

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

由于是三个img,每个显示延迟3000,而fadeOut默认需要400毫秒,所以延迟应该是:

3*3000+400 = 9400

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

【讨论】:

  • 只是出于好奇,您为什么选择9400
  • @Paul 编辑答案。
【解决方案2】:

最好的办法是使用承诺:

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

-jsFiddle-

【讨论】:

  • 确实,我怎么没想到!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-02
  • 2019-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多