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

后端 未结 2 1766
别跟我提以往
别跟我提以往 2021-01-31 17:52

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

2条回答
  •  花落未央
    2021-01-31 18:43

    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.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();
    });
    

提交回复
热议问题