向下滚动时使用 jQuery 显示“返回顶部”链接元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5980237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:09:14  来源:igfitidea点击:

Show "Back to top" link element using jQuery when you scroll down

jqueryscroll

提问by chubbyk

I want to mimic behaviour with jQuery like you can see here: http://edo.webmaster.am/

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

Just look at the right bottom corner, scroll down a bit and you'll see the "back to top" button.

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

So it's invisible until you scroll down a page and then it appears (animated).

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

How can I do that in jQuery ?

我怎样才能在 jQuery 中做到这一点?

回答by Robert

You can monitor the current window scroll position and act accordingly. If you want the offset to be after a certain point (the below code will do any scrolling, even 1px) then just check that $(this).scrollTop() > nin the if statement, where n is the desired offset.

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

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

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

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

回答by Roumelis George

Old question but I thought since I implemented one for myself to give my two cents. I believe it is better to use a setTimeout to safeproofing against multiple triggered events. Like this:

老问题,但我想,因为我为自己实现了一个给我的两美分。我相信最好使用 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();
});