【问题标题】:jQuery image fader doesn't stop when the window loses focus当窗口失去焦点时,jQuery图像推子不会停止
【发布时间】: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


【解决方案1】:

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

$(window).focus(function() {
    if(!animating) {
        anim();
    }
});

在 anim() 函数中设置 animating = true,在 stopFader() 函数中设置 animating = false。所以每次你关注 $(window) 时,它都会检查 anim() 是否正在运行,如果没有,它会启动 anim() 函数。

【讨论】:

    猜你喜欢
    • 2011-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 2019-01-29
    • 2013-11-26
    相关资源
    最近更新 更多