【发布时间】:2015-01-15 10:32:42
【问题描述】:
我有一个简单的 jQuery 图像推子,只是循环图像进出焦点。
这是一支笔:http://codepen.io/designsoutheast/pen/xbqjZL
这是褪色背后的代码:
$('img.bgfade').hide();
function anim() {
$(".slider img.bgfade").first().appendTo('.slider').fadeOut(1000);
$(".slider img").first().fadeIn(10);
setTimeout(anim, 3500);
}
anim();
});
它工作正常,但是当窗口或选项卡失去焦点一段时间后,我返回它时,动画已排队并闪烁不同的图像/发狂直到赶上。
我尝试过使用 jQuery 可见性插件,但无法让它工作。我也尝试过使用标准(窗口).blur ..但我不确定如何在这段时间内正确停止动画。我试过 clearTimeout,但我认为我做错了。这是我尝试过的:
var faderVar;
function anim() {
$(".slider img.bgfade").first().appendTo('.slider').fadeOut(1000);
$(".slider img").first().fadeIn(10);
faderVar = setTimeout(function() {anim}, 3500);
}
function stopFader() {
clearTimeout(faderVar);
}
anim();
$(window).focus(function() {
var faderVar;
function anim() {
$(".slider img.bgfade").first().appendTo('.slider').fadeOut(1000);
$(".slider img").first().fadeIn(10);
faderVar = setTimeout(function() {anim}, 3500);
}
function stopFader() {
clearTimeout(faderVar);
}
anim();
});
$(window).blur(function() {
stopFader();
});
我认为我在正确的轨道上,但我对 jQuery 很陌生,我很确定 clearTimeout 写错了。希望有人能帮忙!
【问题讨论】:
-
你必须使用变量来设置超时。 w3schools.com/jsref/met_win_cleartimeout.asp
-
您好,感谢您的回复!我尝试使用您发布的链接中的示例,我已将修改后的代码添加到我的原始帖子中!这里有一个显示它的代码笔:codepen.io/designsoutheast/pen/xbqjZL 但是它不起作用。我觉得我越来越接近了,我对使用 Javascript 和 jQuery 还是很陌生,所以为我的无知道歉! :)
标签: javascript jquery window focus