JS 自动滚动页面到底部

目录
function getScrollTop() {
    var scrollTop = 0,
        bodyScrollTop = 0,
        documentScrollTop = 0;
    if (document.body) {
        bodyScrollTop = document.body.scrollTop;
    }
    if (document.documentElement) {
        documentScrollTop = document.documentElement.scrollTop;
    }
    scrollTop =
        bodyScrollTop - documentScrollTop > 0
            ? bodyScrollTop
            : documentScrollTop;
    return scrollTop;
}

function getScrollHeight() {
    var scrollHeight = 0,
        bodyScrollHeight = 0,
        documentScrollHeight = 0;
    if (document.body) {
        bodyScrollHeight = document.body.scrollHeight;
    }
    if (document.documentElement) {
        documentScrollHeight = document.documentElement.scrollHeight;
    }
    scrollHeight =
        bodyScrollHeight - documentScrollHeight > 0
            ? bodyScrollHeight
            : documentScrollHeight;
    return scrollHeight;
}

function getWindowHeight() {
    var windowHeight = 0;
    if (document.compatMode == "CSS1Compat") {
        windowHeight = document.documentElement.clientHeight;
    } else {
        windowHeight = document.body.clientHeight;
    }
    return windowHeight;
}

//
function autoScroll() {
    if (getScrollTop() + getWindowHeight() < getScrollHeight()) {
        window.scrollTo({
            top: window.scrollY + 5,
            behavior: "smooth",
        });
        var timerId = setTimeout(autoScroll, 50);
        // stop when click
        document.addEventListener("click", (event) => {
            window.clearInterval(timerId);
        });
    }
}
autoScroll();

通过浏览器标签(Bookmarklet方式)调用,拖拽下面的链接到浏览器标签栏:

可在阅读网页时,使用自动滚动功能,让鼠标手小憩一会儿。