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

无限滚动首次滚动后页码自动递增,如何实现仅滚动时加载对应页数据

问题根因

  • 缺少加载状态锁:fetch是异步操作,调用loadData后数据还没完成渲染、页面高度还没更新时,滚动事件仍会持续触发,且你在调用loadData后立刻执行了currentPage++,导致满足条件时会连续发起多次加载请求
  • 滚动触底判断逻辑错误:原判断没有计入浏览器视口高度,触发条件计算偏差,导致只要滚动到对应位置就会反复触发判断

修复方案

核心修改点

  1. 新增isLoading变量标记加载状态,加载完成前不再响应新的加载请求
  2. 修正滚动触底的判断逻辑,加入视口高度计算
  3. 把currentPage++的操作移到请求成功、数据渲染完成之后,避免页码提前更新
  4. 加载完成后重置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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 11:36:07