【问题标题】:delay() or timeout with stop()?延迟()或停止()超时?
【发布时间】:2011-03-20 17:48:33
【问题描述】:
$('.file a').live('mouseenter', function() {
    $('#download').stop(true, true).fadeIn('fast');
}).live('mouseleave', function() {
    $('#download').stop(true, true).fadeOut('fast');
});

我希望 mouseenter 函数具有 stop() 和 1 秒的延迟。 所以,如果我将鼠标悬停在#download 上,fadeIn 应该会在 1 秒延迟后启动。如果我同时将鼠标移开,fadeIn 不应该启动。找我?

我真的不知道该怎么做,有什么想法吗?

【问题讨论】:

  • @user239831 - 你对此有什么悬而未决的问题吗?

标签: javascript jquery hover delay


【解决方案1】:

在这种情况下,您需要使用 setTimeout(),因为 .delay() 的工作原理(以及您无法取消它)。

$('.file a').live('mouseenter', function() {
  $.data(this, 'timer', setTimeout(function() {
      $('#download').stop(true, true).fadeIn('fast');
  }, 1000));
}).live('mouseleave', function() {
  clearTimeout($.data(this, 'timer'));
  $('#download').stop(true, true).fadeOut('fast');
});

You can give it a try here.

如果您使用.delay(),它将使元素的下一个动画出列,无论您是否之前清除了该队列。所以你需要一个你可以取消的超时,上面通过手动调用setTimeout()并将结果存储在$.data()中,这样你以后可以通过clearTimeout()清除它。

【讨论】:

  • 优秀。延迟非常重要。我仍然知道无法取消,这意味着应该非常小心地使用它。这是处理这个问题的好方法。谢谢。
  • 嗨。我在this jsFiddle 中为slideDown()slideUp() 尝试相同的方法,但效果不佳。你能告诉我我在这里错过了什么吗?注意:我正在尝试不使用hoverIntent() 函数。
  • 来自文档:从 jQuery 1.7 开始,.live() 方法已被弃用。使用.on() 附加事件处理程序。
【解决方案2】:

我正在寻找类似问题的答案,我发现 .animate() 也可以用来处理这个问题,它服从 .stop()

看起来像这样:

$('.file a').live('mouseenter', function() {
    $('#download')
        .stop(true, true)
        .animate({opacity:0}, 1000);            // one second delay
        .animate({opacity:1}, 'fast', 'swing');
}).live('mouseleave', function() {
    $('#download')
        .stop(true, true)
        .animate({opacity:0}, 'slow', 'swing');
});

【讨论】:

    【解决方案3】:

    使用 setTimeout 函数

    $('.file a').live('mouseenter', function() {
    setTimeout(function(){
        $('#download').stop(true, true).fadeIn('fast');
    }, 1000);
    }).live('mouseleave', function() {
        $('#download').stop(true, true).fadeOut('fast');
    });
    

    setTimeout 将在指定的毫秒(在本例中为 1000)后执行函数内的代码。

    【讨论】:

    • 您还需要存储/清除该超时,如果您快速进出鼠标,它将在 200 毫秒内完成淡出()(如果它运行的话),然后在 800 毫秒后有一个排队淡入,即使你没有超过元素。看看这里,看看我的意思:jsfiddle.net/nick_craver/T9t6N 要测试,快速悬停并离开链接。
    【解决方案4】:

    你可以在 jquery 上使用它而不使用延迟事件。

    $('.file a').hover(function() {
      time = setTimeout(function() {
         $('#download').fadeIn();
      },1000);
    },function(){
        clearTimeout(time);
    });
    

    1000 是您的时间,之后 $('#download') 将淡入。

    【讨论】:

      猜你喜欢
      • 2014-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多