[英]Stop a jquery loop function on click while adding class
我有一個函數,該函數在類處於活動狀態時連續遍歷一組div(請參見下文)。 我正在嘗試修改該函數,以便當您單擊div時,它將停止循環並將活動類添加到該div。
我在StackOverflow上瀏覽了無數示例,但未能找到適合我情況的東西。
我要修改的功能:
function doLoop() {
$('.cd-types, .img-frame, .img-content-container').each(function(){
(function($set){
setInterval(function(){
var $cur = $set.find('.active').removeClass('active');
var $next = $cur.next().length ? $cur.next() : $set.children().eq(0);
$next.addClass('active');
},7000);
})($(this));
});
}
這里是jfiddle與我的修改循環的嘗試。 我知道它相當簡單,並且我花了最后幾個小時來弄清楚它。 任何建議/方向將不勝感激。
嘗試
function doLoop() {
$('.cd-types, .img-frame, .img-content-container, .list-items').each(function () {
var $set = $(this);
var interval = setInterval(function () {
var $cur = $set.find('.active').removeClass('active');
var $next = $cur.next().length ? $cur.next() : $set.children().eq(0);
$next.addClass('active');
}, 1000);
$set.data('loop', interval);
$set.on('click', '> *', function () {
$(this).addClass('active').siblings('.active').removeClass('active');
clearInterval($set.data('loop'));
$set.removeData('loop')
});
});
}
使用“ self”變量技巧可以稍微簡化循環功能。
使用timerID跟蹤setInterval()調用,以便在單擊時可以使用clearInterval()調用將其停止:
$('.list-items').children().first().addClass('active');
var timerID;
$('.list-items').each(function () {
var self = this;
timerID = setInterval(function () {
var $cur = $(self).find('.active').removeClass('active');
var $next = $cur.next().length ? $cur.next() : $(self).children().eq(0);
$next.addClass('active');
}, 1000);
});
$('.list-items').on('click', function(){
clearInterval(timerID);
alert("Stopped");
});
請參閱以下工作代碼:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.