Javascript 让JQuery幻灯片只迭代一次?
所以我想每两秒钟做一次图片切换的幻灯片,我有这个代码 HTML:Javascript 让JQuery幻灯片只迭代一次?,javascript,jquery,html,Javascript,Jquery,Html,所以我想每两秒钟做一次图片切换的幻灯片,我有这个代码 HTML: <div class="fadeIn"> <img src="img/city.png" class="remimg" id="city"> <img src="img/shop.png" class="remimg" id="shop"> <img src="img/ice-cream-cone.png" class="remimg" id="icecream"&
<div class="fadeIn">
<img src="img/city.png" class="remimg" id="city">
<img src="img/shop.png" class="remimg" id="shop">
<img src="img/ice-cream-cone.png" class="remimg" id="icecream">
</div>
如何使它只迭代一次 您可以设置计数器,将间隔分配给变量,然后清除间隔 修改javascript,如下所示:
$(function(){
$('.fadeIn img:gt(0)').hide();
// assign this to a variable, since we're going to check it often
var total = $('.fadeIn img').length;
// initialize the counter
// You can adjust this number as desired.
// For example, set it to 0 if you want the show to end on the first slide
var count = 1;
// assign the interval to a variable so we can clear it
var slideInterval = setInterval(function() {
// if the current slide count is equal to or greater than the total slides, clear the interval
if (++count >= total) {
// stops the slideInterval (and therefore the slideshow)
clearInterval(slideInterval);
// You could do other things here if desired....
}
$('.fadeIn :first-child').fadeOut()
.next('img').fadeIn()
.end().appendTo('.fadeIn');},
2000);
});
使用递归函数而不附加图像,然后在到达最后一个图像时停止,可能更容易
$(function() {
var all = $('.fadeIn img'),
first = all.first(),
last = all.last();
all.not(first).hide();
(function fn(image) {
setTimeout(function() {
var f = image.fadeOut().next().fadeIn();
if ( f.get(0) !== last.get(0) ) fn(f);
}, 2000);
}(first));
});
$(function() {
var all = $('.fadeIn img'),
first = all.first(),
last = all.last();
all.not(first).hide();
(function fn(image) {
setTimeout(function() {
var f = image.fadeOut().next().fadeIn();
if ( f.get(0) !== last.get(0) ) fn(f);
}, 2000);
}(first));
});