js 判断滚动到底部 自动加载

HTML 结构

<!-- 滚动到底部提示区域 -->
<section class="bottom-tip" v-if="bottomTip">
  {{bottomTipText}}
</section>

<!-- 数据为空的提示区域 -->
<div class="no-data" v-if="noData">
  暂无数据
</div>

CSS 样式

// 底部加载更多样式
.bottom-tip{
  padding:.25rem 0;
  text-align:center;
}

JavaScript 变量声明

// 用于控制是否显示底部提示和提示文本
bottomTip: false,
bottomTipText: '',

// 页面相关信息,包括分页和数据状态
pages: {
  // 是否没有数据
  noData: false,
  // 每页显示的数据条数
  page_size: 30,
  // 当前页码
  page: 1,
  // 总的页码数量
  last_page: 1
}
// 监听浏览器滚动事件
// 监听浏览器滚动事件以加载更多数据
window.addEventListener('scroll', () => {
  // 获取滚动条当前位置
  let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  // 获取可视区域高度
  let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
  // 获取整个文档的高度
  let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;

  // 检查是否滚动到页面底部,若是则调用 loadmore 函数
  if(scrollHeight > clientHeight && Math.ceil(scrollTop + clientHeight) >= scrollHeight) {
    this.loadmore();
  }
});


// 加载更多数据函数
loadmore() {
  // 检查当前页是否小于最后一页
  if (this.pages.last_page > this.pages.page) {
    this.pages.page++;
    this.history();
  }
}

// 数据获取与处理
xxx () {
  // 设置加载中的提示文本
  this.bottomTipText = '加载中...';

  // 调用 API 获取数据
  this.Api.xxx(this.pages, this.urlType).then( response => {
    if (response['success']) {
      this.bottomTip = true;
      this.bottomTipText = '滑动加载更多...';
      this.pages.last_page = response['data']['last_page'];

      // 检查是否到达最后一页
      if (response['data']['last_page'] <= this.pages.page) {
        this.bottomTipText = '暂无更多数据...';
        // 检查数据是否为空
        if(!data.length) {
          this.noData = true;
          this.bottomTip = false;
        } else {
          this.noData = false;
        }
      }
    }
  })
}

posted on   完美前端  阅读(644)  评论(0编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示