【发布时间】:2021-08-21 00:10:03
【问题描述】:
我正在尝试制作一个无限滚动页面。该脚本在我的计算机(Chrome)上运行良好,但在我朋友的计算机(Chrome 也是)上运行良好。当底部的内容通过ajax附加时,我看到它在检测页面底部时确实有效。
我还看到,一旦我更改页面的宽度(只需移动 chrome 的控制台窗口),加载内容就会起作用。
我猜这是因为 js 没有考虑到 DOM。
有什么想法吗?
start += limit;
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
$(document).bind("scroll", function() {
if(($(window).scrollTop() + $(window).height()) == $(document).height() || agentID && ($(window).scrollTop() + $(window).height()) + 200 > $(document).height()) {
load($("#search").val(), start, limit)
start += limit;
console.log("End of page detected")
}
});
function load(search, start=0, limit=20) {
$("#loader_active").show()
let form_data = new FormData();
form_data.append('search', search);
form_data.append('start', start);
form_data.append('limit', limit);
$.ajax({
url: "http://website.com/ajax/videos.php",
contentType: false,
dataType: "json",
processData: false,
cache: false,
data: form_data,
type: 'POST',
success: function (data) {
$(data).each(function(index, value) {
showVideo(value) // show video creates divs with jquery containing the data from the json received by the ajax call
})
$("#loader_active").hide()
}
})
}
【问题讨论】:
-
您的
if条件似乎是A || B && CC。意图是(A || B) && C还是A || (B && C)?您可以尝试调试该条件及其值。见Which Logic Operator Takes Precedence。 -
对应A || (B && C),但这不是问题的根源。只是尝试使用 A 会导致同样的问题。我几乎可以肯定它来自 DOM,并且在使用 ajax 添加内容后,滚动事件无法计算滚动条的新高度。但我不知道如何解决它。
-
看起来像
$(document).height()这样的值在每次滚动事件触发时都会被评估,因此它们应该反映动态内容。是否可以建立一个working demo 来帮助重现该问题?也许您可以使用 reqres.in 之类的东西通过 AJAX 生成示例数据。如需参考,另请参阅Check if a user has scrolled to the bottom。
标签: javascript jquery dom scroll