我正在尝试使用三张幻灯片创建一个滑块.最初,幻灯片将显示为循环.我的目标是,如果#fancy_1单击一个按钮,将停止具有函数名称"runem"的循环,并且循环将在那里结束.我尝试过stop(true,true),但没有成功.无论是否单击该按钮,循环始终在运行.有谁知道如何实现这一目标?
(function($) {
$(document).ready(function() {
function runem() {
var allofEm = $('.j_fancy .j_fancy_block');
var $active = allofEm.eq(0);
$active.show();
var $next = $active.next();
var timer = setInterval(function() {
$next.fadeIn();
$active.hide();
$active = $next;
$next = (allofEm.last().index() == allofEm.index($active)) ?
$next = allofEm.eq(0) : $active.next();
}, 5000);
}
runem();
$("#fancy_1").click(function() {
$('.j_fancy_block').eq(0).show();
$('.j_fancy_block').eq(1).hide();
$('.j_fancy_block').eq(2).hide();
runem().stop(true, true); //this doesn't work.
})
$("#fancy_2").click(function() {
$('.j_fancy_block').eq(0).hide();
$('.j_fancy_block').eq(1).show();
$('.j_fancy_block').eq(2).hide();
runem().stop(true, true); //this doesn't work.
})
$("#fancy_3").click(function() {
$('.j_fancy_block').eq(0).hide();
$('.j_fancy_block').eq(1).hide();
$('.j_fancy_block').eq(2).show();
runem().stop(true, true); //this doesn't work.
})
})
}(jQuery));
Run Code Online (Sandbox Code Playgroud)
你试过用过clearInterval()吗?stop()不工作的原因是因为这是一个停止jQuery动画的功能,而不是Javascript setInterval- 因此setInterval将继续运行
我建议使用它的方式是这样的......
var boxInterval;
function runem(){
/*Function Stuff*/
boxInterval = setInterval(function(){...});
}
function stopBox(){
clearInterval(boxInterval);
}
Run Code Online (Sandbox Code Playgroud)
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval#Example