我正在尝试使用jQuery设计幻灯片,但是我想出了下面的代码,但是,当我运行它时,它只能循环浏览一张幻灯片,然后停止做任何进一步的事情。如何使图片循环显示?
jQuery的:
$(function() {
setInterval("rotateImages()", 3000);
});
function rotateImages() {
var CurrentPhoto = $('#slideshow .current');
var NextPhoto = CurrentPhoto.next();
if (NextPhoto.length == 0) {
NextPhoto = $('#slideshow div:first');
}
CurrentPhoto.removeClass('current').addClass('previous');
NextPhoto.css({ opacity: 0.0 }).addClass('current')
.animate({ opacity: 1.0 }, 1000,
function() {
CurrentPhoto.removeClass('previous');
}
}
HTML:
<div id="slideshow">
<div class="current"><img src="image1.jpg" alt="Img" height="382" width="594"> </div>
<div><img src="image2.jpg" alt="Img" height="382" width="594"> </div>
<div><img src="image3.jpg" alt="Img" height="382" width="594"></div>
<div><img src="image4.jpg" alt="Img" height="382" width="594"></div>
<div><img src="image5.jpg" alt="Img" height="382" width="594"></div>
</div>
...
CSS:
#slideshow div {
z-index: 0;
position: absolute;
margin: 0px 0px 0px 362px;
}
#slideshow div.previous {
z-index: 1;
}
#slideshow div.current {
z-index: 2;
}
最佳答案
您的脚本中有两个错误:
缺少括号(您可能在JavaScript控制台中很容易看到),以关闭animate
函数。NextPhoto == 0
不正确。您要检查NextPhoto
的长度是否为0,而不是NextPhoto
本身。
修复这两个问题,即可解决问题:
$(function() {
setInterval("rotateImages()", 3000);
});
function rotateImages() {
var CurrentPhoto = $('#slideshow .current');
var NextPhoto = CurrentPhoto.next();
if (NextPhoto.length == 0) {
NextPhoto = $('#slideshow div:first');
}
CurrentPhoto.removeClass('current').addClass('previous');
NextPhoto.css({ opacity: 0.0 }).addClass('current')
.animate({ opacity: 1.0 },
1000,
function() {
CurrentPhoto.removeClass('previous');
});
}
在此JSFiddle上看到它:http://jsfiddle.net/h7afu5ex/