scroll down page by the height of current viewport

2019-05-10 23:19发布

问题:

I have a page in which I have a fixed positioned button, which when clicked should calculate the height of the viewport, and then scroll down the page by that height. ie. to the next viewport. When the user reaches the point when there is no more room to scroll I want to hide this button. Not sure how to do this, so far I have this:

$(document).on('click', '.next-viewport-down', function(event){                        
                     event.preventDefault();
                     var viewportHeight = $(window).height();

                         $('html, body').stop(true,true).animate({
                                 .....
                             }, 2000);
            });

回答1:

Try this.

$(document).on('click', '.next-viewport-down', function(event){                        
    event.preventDefault();
    var viewportHeight = $(window).height();

    $('html, body').animate({
        scrollTop: viewportHeight,
        complete: function () {
            //Hide your button here
        }
    }, 2000);
});


回答2:

You can use this to keep track of the current section and continue:

var currentSection = 0;
var totalSections = document.querySelectorAll("section").length;
$(document).on('click', '.next-viewport-down', function(event){                        
    event.preventDefault();
    var viewportHeight = $(window).height();
    currentSection++;
    if (currentSection > totalSections - 1) currentSection = totalSections - 1;
    $('html, body').animate({
        scrollTop: viewportHeight * currentSection,
        complete: function () {
           $('.next-viewport-down').slideDown(300);
        }
    }, 500);
});


标签: jquery scroll