我使用 jQuery 创建了一个图像幻灯片,其中 5 张图像在 25 秒的间隔内一个接一个地出现。每张图片在淡出前保持 5 秒,然后下一张图片淡入。
幻灯片效果很好,但我希望它永远循环,即在最后图像淡出后,它应该重新开始第一张图片的动画。
我尝试使用 setInterval
但没有成功。这是我编写的幻灯片的工作示例:
完整代码如下:
HTML:
<img id="img1" src="http://njballroomdancecenter.com/wp-content/uploads/2013/08/1500x1000.jpg" style="display: block; width: 50%; position: absolute;" />
<img id="img2" src="http://njballroomdancecenter.com/wp-content/uploads/2013/08/1500x1000-1.jpg" style="display: block; width: 50%; position: absolute;" />
<img id="img3" src="http://njballroomdancecenter.com/wp-content/uploads/2013/08/1500x1000-2.jpg" style="display: block; width: 50%; position: absolute;" />
<img id="img4" src="http://njballroomdancecenter.com/wp-content/uploads/2013/08/1500x1000-3.jpg" style="display: block; width: 50%; position: absolute;" />
<img id="img5" src="http://njballroomdancecenter.com/wp-content/uploads/2013/08/1500x1000-4.jpg" style="display: block; width: 50%; position: absolute;" />
Javascript:
$(document).ready(function(){
$("#img2,#img3,#img4,#img5").hide();
setTimeout(function(){
$("#img1").fadeOut("slow", function () {});
}, 5000);
setTimeout(function(){
$("#img2").fadeIn("slow", function () {});
}, 5000);
setTimeout(function(){
$("#img2").fadeOut("slow", function () {});
}, 10000);
setTimeout(function(){
$("#img3").fadeIn("slow", function () {});
}, 10000);
setTimeout(function(){
$("#img3").fadeOut("slow", function () {});
}, 15000);
setTimeout(function(){
$("#img4").fadeIn("slow", function () {});
}, 15000);
setTimeout(function(){
$("#img4").fadeOut("slow", function () {});
}, 20000);
setTimeout(function(){
$("#img5").fadeIn("slow", function () {});
}, 20000);
setTimeout(function(){
$("#img5").fadeOut("slow", function () {});
}, 25000);
});
最佳答案
jQuery(function( $ ){ // DOM ready shorthand
// ::: Fade Gallery: http://stackoverflow.com/a/18454450/383904
var $gal = $("#gallery"),
$img = $gal.find(">*"),
n = $img.length, // number of images
c = 0, // counter
itv; // loop interval
function anim(){ $img.fadeOut().eq( ++c % n ).stop().fadeIn(); }
function loop(){ itv = setInterval(anim, 3000); }
function stop(){ clearInterval( itv ); }
$img.hide().eq(c).show(); // Begin with `c` indexed image
$gal.hover( stop, loop ); // Pause gallery on hover
loop(); // START!
});
#gallery { position:relative; }
#gallery img { position:absolute; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(Hover to pause gallery)<br>
<div id="gallery">
<img src="//placehold.it/200x130/993/fff?text=1" />
<img src="//placehold.it/200x130/379/fff?text=2" />
<img src="//placehold.it/200x130/973/fff?text=3" />
<img src="//placehold.it/200x130/739/fff?text=4" />
<img src="//placehold.it/200x130/793/fff?text=5" />
</div>
关于javascript - 如何无限循环 jQuery 画廊,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18454253/