2010-01-04 234 views
0

我试图创建自己的幻灯片。以下代码从一个图像变为另一个图像。我想循环从img1.jpg到img4.jpg,但我不知道如何在每次更改后暂停。jQuery幻灯片

   i++; 
       temp = "img"+i+".jpg"; 
       $("#img").fadeOut(function() { 
        $(this).load(function() { $(this).fadeIn(); }); 
        $(this).attr("src", temp); 
       }); 

更新:我已将代码更改为以下内容。在John Boker的建议下,我将图像更名为img0,img1,img2,img3。它到达了第一,第二,第三个图像。有任何想法吗?

<html> 
    <head> 
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
     <script> 

      $(document).ready(function(){   
       var temp=""; 

       function slideshow(i) 
       { 
        temp = "img"+i+".jpg"; 
        $("#img").fadeOut(function() { 
         $(this).load(function() { 
            $(this).fadeIn(); 
            // set a timeout of 5 seconds to show the next image; 
            setTimeout(function(){ slideshow((i+1)%4); }, 5000); 
         }); 
         $(this).attr("src", temp); 
        }); 
       } 

       slideshow(0); 


      }); 

     </script> 
    </head> 
    <body> 
     <img src="img1.jpg" id="img"/> 
    </body> 
</html> 

回答

2

你可以像这样做,使用setInterval

$(function() { 

    var i = 0; 

    // Four-second interval 
    setInterval(function() { 
     $("#img").fadeOut(function() { 
      $(this).attr("src", "img" + i++ % 4 + ".jpg"); 
      $(this).fadeIn(); 
     }); 
    }, 4000); 
} 

我已经简化了一些可能导致您正在寻找的其他问题的一些事情,将(看起来多余的)电话转到load内部您的fadeOut回调和消除不必要的temp变量。

(最后,如果你不只是这样做是为了学习,可以考虑使用许多优秀的幻灯片插件之一在那里,像Cycle

+0

工程很好,但如何可以循环,所以当它到达img4它回到img1。我尝试了一个if语句,但无法使其工作。谢谢。 – usertest 2010-01-04 20:22:25

+0

糟糕,我应该提到'i'变量必须在函数之外进行初始化,以便每次函数执行时都不会在本地范围内重新初始化。修改后的代码应该可以工作 – 2010-01-04 20:28:06

0

设立window.setInterval(function, delay)在设定的时间间隔来调用一个函数来执行你的代码。

有很多插件已经为你循环图像(除非挑战是写你自己的),我最喜欢的其中一个是cycle plugin

2

你应该有一个函数内部:

// show image i 
function slideshow(i) 
{ 
    temp = "img"+i+".jpg"; 
    $("#img").fadeOut(function() { 
     $(this).load(function() { 
        $(this).fadeIn(); 
        // set a timeout of 5 seconds to show the next image; 
        setTimeout(function(){ slideshow((i+1)%4); }, 5000); 
     }); 
     $(this).attr("src", temp); 
    }); 
} 
+0

谢谢,它的工作原理,但与Jeff Sternal's有同样的问题 - 它不会循环。如何在img4之后回到img1。我无法获得if语句来执行此操作。 – usertest 2010-01-04 20:24:03

+0

如果我是你,我会从0开始,所以它会更容易使用模数。 (i + 1)%4会让你的周期,所以如果我= 3,(3 + 1)%4 = 0.你的图像将被命名为img0.jpg,img1.jpg,img2.jpg,img3.jpg – 2010-01-04 20:33:45

0

一个技巧就是用一个动画元素的属性其当前值使用计时器。

$("#img").fadeIn().show(3000).fadeOut(); 

因为$(这)已经可见,加入.show(3000)意味着元素淡出

2

试试下面这个例子之前,保持3秒可见.. 。

$(function(){ 
    $('.slideshow img:gt(0)').hide(); 
    setInterval(function(){$('.slideshow :first-child').fadeOut(2000).next('img').fadeIn(2000).end().appendTo('.slideshow');}, 4000); 
}); 

A fiddle

只需在脚本中将4000更改为8000即可,如果要将每个图像暂停8秒而不是4秒。