Show “Back to top” link element using jQuery when

2019-03-09 01:48发布

I want to mimic behaviour with jQuery like you can see here: 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 scroll
2条回答
Evening l夕情丶
2楼-- · 2019-03-09 02:40

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:

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();
});
查看更多
smile是对你的礼貌
3楼-- · 2019-03-09 02:45

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() > n in the if statement, where n is the desired offset.

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

$(window).scroll(function() {
    if ($(this).scrollTop()) {
        $('#toTop:hidden').stop(true, true).fadeIn();
    } else {
        $('#toTop').stop(true, true).fadeOut();
    }
});
查看更多
登录 后发表回答