这就是我想要完成的:当到达最后一张幻灯片时,先淡出最后一张幻灯片,然后淡入第一张幻灯片,然后是 clearInterval (这部分一切正常)。现在我的问题是,如果它不存在,我想 again 设置它,但我不知道如何实现它:(
我试图用 if 语句解决这个问题,但是那么我的脚本根本不起作用!
那么我怎样才能重新开始我的间隔呢?谢谢!
没有这样的if语句它工作正常:
if(!intervalID){
intervalID = setInterval(animate,5000);
}
这是我目前所拥有的:
$(document).ready(function() {
/*check if intervalID don't exists messes UP!!*/
if (!intervalID) {
intervalID = setInterval(animate, 5000);
}
//Hide everything except first slide and controls
$('.slidewrap div:not(.slidewrap div:first,.slidewrap .slide_controls)').hide();
var animate = function() {
/*if .pagination_active is last removeClass and addClass to .pagination_active
first li tag*/
if ($('.pagination_active').is($('.slide_controls ul li:last'))) {
$('.pagination_active').removeClass('pagination_active');
$('.slide_controls ul li:first').addClass('pagination_active');
} else {
$('.pagination_active').removeClass('pagination_active').next().addClass('pagination_active');
}
/*if div.active is last fadeOut and add .active class
to the first div and fadeIn FIRST div then CLEAR INTERVAL and set intervalID to zero */
if ($('.active').is($('.slidewrap div:last'))) {
$('.active').fadeOut(1000).removeClass('active');
$('.slidewrap div:first').addClass('active').fadeIn(1000, function() {
clearInterval(intervalID);
intervalID = 0;
});
}
//OR .active fadeOut and next div fadeIn
else {
$('.active').fadeOut(1000).next().fadeIn(1000, function() {
$('.slidewrap div.active').removeClass('active').next('div').addClass('active');
});
}
}
var intervalID;
intervalID = setInterval(animate, 3000);
});
最佳答案
清除间隔后,您需要使用 setInterval()
重新开始。
最好为你的setInterval()
做函数
var intervalID = null;
function intervalManager(flag, animate, time) {
if(flag)
intervalID = setInterval(animate, time);
else
clearInterval(intervalID);
}
这里的 flag
是一个 boolean
变量,值为 true/false
。 true
将执行 setInterval()
,false
将执行 clearInterval()
;
现在您可以根据需要使用上述功能。
例如:
intervalManager(true, animate, 300); // for setInterval
intervalManager(false); // for clearInterval
关于javascript - 如何清除间隔并重新设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10935026/