2011-05-12 36 views

回答

62

您可以监视当前窗口滚动位置并相应地执行操作。如果您希望偏移量在某个点之后(下面的代码将执行任何滚动,甚至1px),那么只需在if语句中检查$(this).scrollTop() > n,其中n是所需的偏移量。

http://jsfiddle.net/robert/fjXSq/

$(window).scroll(function() { 
    if ($(this).scrollTop()) { 
     $('#toTop:hidden').stop(true, true).fadeIn(); 
    } else { 
     $('#toTop').stop(true, true).fadeOut(); 
    } 
}); 
+0

真棒解决方案!像任何东西一样容易... – 2012-11-15 00:42:03

+0

谢谢。这个解决方案很容易使用和理解! – 2014-03-17 07:30:37

+0

为了确保你不会遇到与'''.scrollTop()'''> n相关的淡出问题,请添加'''if($('#toTop')。css('display')== none )在'''.fadeOut()'''之前'' – thewisenerd 2015-05-04 18:32:20

1

老问题,但我想,既然我实现了一个为自己给我的两分钱。我相信最好使用setTimeout来防止多个触发事件的安全。像这样:

function showButton() { 


    var button = $('#my-button'), //button that scrolls user to top 
     view = $(window), 
     timeoutKey = -1; 

    $(document).on('scroll', function() { 
     if(timeoutKey) { 
      window.clearTimeout(timeoutKey); 
     } 
     timeoutKey = window.setTimeout(function(){ 

      if (view.scrollTop() < 100) { 
       button.fadeIn(); 
      } 
      else { 
       button.fadeOut(); 
      } 
     }, 100); 
    }); 
} 

$('#my-button').on('click', function(){ 
    $('html, body').stop().animate({ 
     scrollTop: 0 
    }, 500, 'linear'); 
    return false; 
}); 

//call function on document ready 
$(function(){ 
    showButton(); 
}); 
相关问题