我在这里设置了一个小提琴:http://jsfiddle.net/bd53ewoh/
当您将鼠标悬停在" .homepage-modules"容器是否可以阻止" next"功能因此它停止循环活动状态,当你将容器悬停在容器上时," next"功能再次开始射击?我此刻有点难过,不知道有办法做到这一点
$('.homepage-modules div:first').addClass('active');
$.fn.cycle = function (timeout, cls) {
var l = this.length,
current = 0,
prev = 0,
elements = this;
if (this.filter('.active').length > 0) {
current = this.index(this.filter('.active')[0]) + 1;
prev = current - 1;
}
function next() {
elements.eq(prev).removeClass('active');
elements.eq(current).addClass('active');
prev = current;
current = (current + 1) % l;
setTimeout(next, timeout);
}
setTimeout(next, timeout);
return this;
};
$('.homepage-modules div').cycle(2000, 'active');
答案 0 :(得分:1)
你的.hover()
div需要一个.homepage-modules
,并且需要一个简单的布尔来处理悬停状态:
var noScrolling = false;
$('.homepage-modules').hover(
function() {
noScrolling = true;
},
function() {
noScrolling = false;
$('.homepage-modules div').cycle(2000, 'active');
}
);
然后,在next()
函数中:
function next() {
if (noScrolling) {
console.log('I shouldn\'t be scrolling through.');
return;
}
// Otherwise, continue
请注意,因为我已将return
投放到您的next()
函数中,它实际上会返回整个$fn.cycle
父函数,因此它会重新初始化当徘徊在div之外。
我在这里更新了您的小提琴:http://jsfiddle.net/bd53ewoh/10/
答案 1 :(得分:1)
您应该将setTimeout
次调用的结果存储在插件中的变量中。当鼠标悬停在元素上时,您可以使用clearTimeout
来停止计时器的运行,当鼠标移出时,您可以再次启动计时器。
$.fn.cycle = function (timeout, cls) {
var l = this.length,
current = 0,
prev = 0,
elements = this,
timerId;
if (this.filter('.active').length > 0) {
current = this.index(this.filter('.active')[0]) + 1;
prev = current - 1;
}
this.parent().hover(function(){
clearTimeout(timerId);
},
function(){
timerId = setTimeout(next, timeout);
})
function next() {
elements.eq(prev).removeClass('active');
elements.eq(current).addClass('active');
prev = current;
current = (current + 1) % l;
timerId = setTimeout(next, timeout);
}
timerId = setTimeout(next, timeout);
return this;
};