无限滚动首次滚动后页码自动递增,如何实现仅滚动时加载对应页数据
问题根因
- 缺少加载状态锁:
fetch是异步操作,调用loadData后数据还没完成渲染、页面高度还没更新时,滚动事件仍会持续触发,且你在调用loadData后立刻执行了currentPage++,导致满足条件时会连续发起多次加载请求 - 滚动触底判断逻辑错误:原判断没有计入浏览器视口高度,触发条件计算偏差,导致只要滚动到对应位置就会反复触发判断
修复方案
核心修改点
- 新增
isLoading变量标记加载状态,加载完成前不再响应新的加载请求 - 修正滚动触底的判断逻辑,加入视口高度计算
- 把
currentPage++的操作移到请求成功、数据渲染完成之后,避免页码提前更新 - 加载完成后重置
isLoading状态,允许后续滚动触发新的加载
修复后完整代码
$(document).ready(function () { let articleText = document.querySelector(".article_ct .text"); let currentPage = 1; let totalPage = 5; // 新增加载状态锁 let isLoading = false; function loadData(page) { // 加锁,避免重复加载 isLoading = true; fetch("index.json") .then((response) => response.json()) .then((result) => { let text = document.createElement("p"); text.style.marginBottom = "100px"; text.innerText = result[page].text; articleText.append(text); history.pushState(null, null, `tes.html?page=${page}`); // 加载成功后页码+1 currentPage++; // 加载完成解锁 isLoading = false; $(".loader").css("display", "none"); }) .catch((error) => { console.log(error); // 异常也要解锁,避免后续无法加载 isLoading = false; $(".loader").css("display", "none"); }); } // 初始化加载第一页 fetch("index.json") .then((response) => response.json()) .then((result) => { let text = document.createElement("p"); text.style.marginBottom = "100px"; text.innerText = result[0].text; articleText.append(text); }) .catch((error) => console.log(error)); $(window).scroll(function () { // 新增判断:如果正在加载中或者已经到最后一页,直接返回不处理 if (isLoading || currentPage > totalPage) { return; } // 修正触底判断:滚动距离 + 视口高度 >= 内容总高度 + 内容顶部偏移 + 提前触发阈值 const scrollBottom = $(this).scrollTop() + $(window).height(); const contentBottom = articleText.offsetTop + articleText.offsetHeight + 100; if (scrollBottom >= contentBottom) { $(".loader").css("display", "block"); loadData(currentPage); } }); });
内容的提问来源于stack exchange,提问作者kentury
相关产品推荐
相关产品推荐

