You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript实现可触发页脚上方滚动加载的自动滚动

解决方案

你原有代码的问题是每次滚动直接走完所有剩余高度,直接跳过了页脚上方的触发区域。调整滚动逻辑,每次滚动后保留100~200px的底部余量即可命中绝大多数站点的无限滚动触发阈值,修改后的代码如下:

(function() {
    var intervalObj = null;
    var retry = 0;
    // 可自定义配置:触发加载的底部余量、滚动间隔
    const TRIGGER_OFFSET = 150;
    const SCROLL_INTERVAL = 1000;
    var lastScrollHeight = document.body.scrollHeight;

    var clickHandler = function() { 
        console.log("Clicked; stopping autoscroll");
        clearInterval(intervalObj);
        document.body.removeEventListener("click", clickHandler);
    }
    function scrollDown() { 
        var scrollHeight = document.body.scrollHeight,
            scrollTop = document.documentElement.scrollTop || document.body.scrollTop,
            innerHeight = window.innerHeight,
            // 计算当前滚动位置距离底部的距离
            distanceToBottom = scrollHeight - (scrollTop + innerHeight);

        // 距离底部大于触发余量时滚动,滚动后刚好停在触发阈值位置
        if (distanceToBottom > TRIGGER_OFFSET) { 
            window.scrollBy(0, distanceToBottom - TRIGGER_OFFSET);
            retry = 0;
            lastScrollHeight = scrollHeight;
            console.log("scrolling to trigger area");
        } else {
            // 检测页面高度是否有变化,判断是否加载了新内容
            if (scrollHeight > lastScrollHeight) {
                retry = 0;
                lastScrollHeight = scrollHeight;
            } else {
                retry++;
                if (retry >= 3) {
                    console.log("reached bottom of page; stopping");
                    clearInterval(intervalObj);
                    document.body.removeEventListener("click", clickHandler);
                } else {
                    console.log(`waiting for new content, retry ${retry}/3`);
                }
            }
        }
    }

    document.body.addEventListener("click", clickHandler);
    intervalObj = setInterval(scrollDown, SCROLL_INTERVAL);
})()

适配说明

  • 部分站点的滚动容器不是body,可以把代码中document.body替换为对应滚动容器的DOM对象即可使用
  • 如果站点触发阈值特殊,可以调整TRIGGER_OFFSET的数值,数值越大滚动后停的位置越靠上,一般取值100~300即可覆盖绝大多数场景

内容的提问来源于stack exchange,提问作者user11004963

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 01:15:04