【问题标题】:"infinite scroll" code working only for top scrolling“无限滚动”代码仅适用于顶部滚动
【发布时间】:2026-01-21 10:55:02
【问题描述】:

我正在使用一个“通用”的 js 片段,它应该检测用户是否已经滚动到文档的底部:

 $(window).scroll(function() {
        if ($(window).scrollTop() == $(document).height() - $(window).height()) {
            //ajax code here
        }
    });

当用户滚动时,新内容应该通过 ajax 调用加载。

我原以为当我向下滚动时代码会触发,但当我滚动回页面顶部时,条件实际上会触发,所以它基本上与“应该”做的相反。

我已经在许多示例中看​​到了此解决方案,例如: https://*.com/a/17078097/1623095

我的调试信息:

console.log($(window).scrollTop());
console.log($(document).height());
console.log($(window).height());

滚动到顶部时的这些输出:

0 
1956 
1956 

底部:

961 
1956
1956 

我的页面中加载的唯一插件是 jquery (1.10.0.min),由于项目的性质,我无法链接到该页面。

完全被这里的 dom 行为搞糊涂了。

【问题讨论】:

    标签: javascript jquery infinite-scroll


    【解决方案1】:

    我之前为别人解决了这个问题。

    看看here:

    代码

    $(window).scroll(function () {
            //- 10 = desired pixel distance from the bottom of the page while scrolling)
            if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
                var box = $("#scrollbox");
                //Just append some content here
                box.html(box.html() + "<br />fa");
            }
    });
    

    Fiddle

    只需将您的 ajax 代码放在我用简单的 html 中断扩展内容的地方

    【讨论】:

    • 您是否感到无聊,或者您一直在改进我的帖子?我认为我们在这里不需要这个重复的答案
    • 当我在任何地方滚动时触发条件,而不仅仅是页面底部,这根本不是理想的结果。
    • 不,它会在您向下滚动并经过测试时触发。你做错了什么。当然,您的滚动元素的高度必须至少与当前浏览器窗口一样高,否则它会认为它已经在底部,因此您应该使用 min-height 作为主要内容容器。