【问题标题】:Show "Back to top" link element using jQuery when you scroll down向下滚动时使用 jQuery 显示“返回顶部”链接元素
【发布时间】:2019-03-26 00:57:30
【问题描述】:

我想模仿 jQuery 的行为,就像你在这里看到的那样: http://edo.webmaster.am/

只需看一下右下角,向下滚动一下,您就会看到“返回顶部”按钮。

所以它是不可见的,直到您向下滚动页面然后它出现(动画)。

如何在 jQuery 中做到这一点?

【问题讨论】:

    标签: jquery scroll


    【解决方案1】:

    您可以监控当前窗口滚动位置并采取相应措施。如果您希望偏移量在某个点之后(下面的代码将进行任何滚动,甚至 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();
        }
    });
    

    【讨论】:

    • 谢谢。该解决方案易于使用和理解!
    • 只是为了确保您不会遇到.scrollTop() > n 的淡出问题,请在.fadeOut() 之前添加if ($('#toTop').css('display') == none)
    • 出于某种原因,已接受答案的第二行中的$(this) 对我不起作用。可能是因为我在 TypeScript Angular 组件中使用它。将 $(this) 更改为 $(window) 对我有用。
    【解决方案2】:

    老问题,但我想,因为我为自己实施了一个给我的两分钱。我相信最好使用 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.fadeOut();
                }
                else {
                    button.fadeIn();
                }
            }, 100);
        });
    }
    
    $('#my-button').on('click', function(){
        $('html, body').stop().animate({
            scrollTop: 0
        }, 500, 'linear');
        return false;
    });
    
    //call function on document ready
    $(function(){
       showButton();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 1970-01-01
      • 2013-08-11
      • 1970-01-01
      • 2023-02-24
      相关资源
      最近更新 更多