Scroll Automatically to the Bottom of the Page

后端 未结 24 2515
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 05:22

Consider I have a list of questions. When I click on the first question, it should automatically take me to the bottom of the page.

For a matter of fact, I do know

24条回答
  •  囚心锁ツ
    2020-11-22 05:49

    Sometimes the page extends on scroll to buttom (for example in social networks), to scroll down to the end (ultimate buttom of the page) I use this script:

    var scrollInterval = setInterval(function() { 
        document.documentElement.scrollTop = document.documentElement.scrollHeight;
    }, 50);
    

    And if you are in browser's javascript console, it might be useful to be able to stop the scrolling, so add:

    var stopScroll = function() { clearInterval(scrollInterval); };
    

    And then use stopScroll();.

    If you need to scroll to particular element, use:

    var element = document.querySelector(".element-selector");
    element.scrollIntoView();
    

    Or universal script for autoscrolling to specific element (or stop page scrolling interval):

    var notChangedStepsCount = 0;
    var scrollInterval = setInterval(function() {
        var element = document.querySelector(".element-selector");
        if (element) { 
            // element found
            clearInterval(scrollInterval);
            element.scrollIntoView();
        } else if((document.documentElement.scrollTop + window.innerHeight) != document.documentElement.scrollHeight) { 
            // no element -> scrolling
            notChangedStepsCount = 0;
            document.documentElement.scrollTop = document.documentElement.scrollHeight;
        } else if (notChangedStepsCount > 20) { 
            // no more space to scroll
            clearInterval(scrollInterval);
        } else {
            // waiting for possible extension (autoload) of the page
            notChangedStepsCount++;
        }
    }, 50);
    

提交回复
热议问题