jQuery 图像推子在窗口失去焦点时不会停止



我有一个简单的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。但我不确定在此期间如何正确停止动画。我已经尝试过清除超时,但我认为我做错了。这是我尝试过的:

        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写错了。希望有人能帮忙!

创建一个名为"animating"(等)的新布尔变量,并将其设置为"var faderVar"之后。清除 $(window).focus() 函数并将其替换为:

$(window).focus(function() {
    if(!animating) {
        anim();
    }
});
在 anim() 函数中设置动画 =

true,在 stopFader() 函数中设置动画 = false。因此,每次您聚焦 $(窗口)时,它都会检查 anim() 是否正在运行,如果不是,它会启动 anim() 函数。

最新更新