【问题标题】:Show scroll button with time-delay显示带有延时的滚动按钮
【发布时间】:2013-02-22 10:55:39
【问题描述】:

我有一个滚动的 div,会显示一个按钮。我希望此按钮在最后一次滚动后仅显示 2 秒。我的脚本中有一个小故障,我无法弄清楚。有时会显示 2 秒,有时会更少,有时会立即隐藏。

我认为的问题是它只从第一个滚动开始计数,之后的每个滚动都不会重置这个计时器,直到它过期。如果计时器到期,则滚动再次显示。

$("#layout-main").live('scroll',function(){
 $("#main-totop").show();
});
$("#main-totop").live('click',function(){
 mainapi.scrollTo(0,0);
 setTimeout(function(){
  $('#main-totop').hide();
 }, 2000); 
});

【问题讨论】:

    标签: jquery scroll timeout hide show


    【解决方案1】:

    这应该可行。

    $("#layout-main").live('scroll',function(){
        $("#main-totop").stop().show(0).delay(2000).hide(0);
    });
    $("#main-totop").live('click',function(){
        mainapi.scrollTo(0,0);
        $('#main-totop').hide();
    });
    

    【讨论】:

    • 你能解释一下有什么不同吗?为什么?
    • 它没有。没有任何东西表明我们需要它在滚动后隐藏 2 秒。需要在#layout-main 事件中处理延迟。
    • 我已经调整了代码以适合您的描述。通过将 1 传递给 .hide 它确实作为动画运行,我们可以使用 jQueries .delay 而不是超时。
    • 是的。它只影响元素上的动画链。这就是为什么hide(0) 不会等待延迟,因为它在内部没有被视为动画,只是切换元素display 值。
    • hide() 不等待,hide(0) 尊重延迟()。似乎只要传递了一个值,它就会将切换视为动画。
    【解决方案2】:

    您应该尝试使用.promise().done(),我建议您使用.on(),因为.live() 是been removed in jQuery version 1.9.0+

    $("#layout-main").on('click', '#main-totop', function(){
       mainapi.scrollTo(0,0).promise().done(function(){
           setTimeout(function(){
               $(this).hide();
           }, 2000);
       });
    });
    

    或者你可以这样尝试:

    $("#layout-main").on('click', '#main-totop', function(){
       mainapi.scrollTo(0,0).promise().done(function(){
          $(this).delay(2000).hide();
       });
    });
    

    【讨论】:

      【解决方案3】:

      您的代码不代表您所描述的内容。

      上面写着:当你在 #layout-main 上滚动时,#main-totop 元素会显示出来。 如果单击则滚动到顶部并在 2 秒后隐藏。

      根据您的描述,您希望按钮(可能是 #main-totop)在最后一次滚动后仅显示 2 秒,然后隐藏。

      如果我是对的,那么你需要这样的东西:

      var mytimer;
      $("#layout-main").live('scroll',function(){
          clearTimeout(mytimer);
          $('#main-totop').show();
          mytimer = setTimeout(function(){
            $('#main-totop').hide();
          }, 2000); 
      });
      $("#main-totop").live('click',function(){
       mainapi.scrollTo(0,0);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-26
        • 2020-12-25
        • 2015-02-15
        • 1970-01-01
        • 2011-04-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多