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

如何根据规则生成分页按钮数字与省略号?

分页按钮标签生成逻辑完整实现

规则回顾

  • 总页数≤4:显示全部页码
  • 总页数=5:
    • 当前页为3时显示全部;当前页<3时显示[1,2,3,...,5];当前页>3时显示[1,...,3,4,5]
  • 总页数=6:
    • 当前页为1/2时显示[1,2,3,...,6];当前页为5/6时显示[1,...,4,5,6];当前页为3/4时显示[1,...,x-1,x,x+1,...,6](x为当前页)
  • 总页数>6:固定显示上一页按钮<、第一页、最后一页;当前页前后各显示一页;首尾与当前页区间有间隔时添加省略号,示例:100页当前33 → ['<', '1', '...', '32', '33', '34', '...', '100']

完整TypeScript实现代码

const getPaginationButtons = (activePage: number, pageCount: number): string[] => {
  // 总页数≤4:显示全部页码
  if (pageCount <= 4) {
    return [...Array(pageCount)].map((_, index) => (index + 1).toString());
  }

  // 总页数=5的逻辑
  if (pageCount === 5) {
    if (activePage === 3) return ['1', '2', '3', '4', '5'];
    if (activePage < 3) return ['1', '2', '3', '...', '5'];
    return ['1', '...', '3', '4', '5'];
  }

  // 总页数=6的逻辑
  if (pageCount === 6) {
    if (activePage <= 2) return ['1', '2', '3', '...', '6'];
    if (activePage >= 5) return ['1', '...', '4', '5', '6'];
    return ['1', '...', (activePage - 1).toString(), activePage.toString(), (activePage + 1).toString(), '...', '6'];
  }

  // 总页数>6的通用逻辑
  const buttons: string[] = ['<'];
  buttons.push('1');

  // 第一页与当前区间的省略号判断
  if (activePage > 3) {
    buttons.push('...');
  }

  // 生成当前页前后的页码(边界处理:不重复显示首尾)
  const start = Math.max(2, activePage - 1);
  const end = Math.min(pageCount - 1, activePage + 1);
  for (let i = start; i <= end; i++) {
    buttons.push(i.toString());
  }

  // 当前区间与最后一页的省略号判断
  if (activePage < pageCount - 2) {
    buttons.push('...');
  }

  buttons.push(pageCount.toString());
  return buttons;
};

关键逻辑说明

  1. 总页数>6的核心处理:

    • 固定保留上一页按钮、第一页和最后一页,保证用户能快速跳转到首尾
    • 通过activePage > 3判断第一页与当前页区间是否有间隔,有则加省略号
    • 通过Math.max(2, activePage-1)和Math.min(pageCount-1, activePage+1)确保当前页前后的页码不会超出有效范围(避免重复显示第一/最后一页)
    • 通过activePage < pageCount - 2判断当前页区间与最后一页是否有间隔,有则加省略号
  2. 边界情况覆盖:

    • 当前页为第一页时:不会显示第一个省略号,直接显示<、1、2、3、...、最后一页
    • 当前页为最后一页时:不会显示第二个省略号,直接显示<、1、...、倒数第三页、倒数第二页、最后一页
    • 当前页在中间区间时:完整显示首尾、省略号、当前页前后各一页

测试示例

  • 输入:activePage=33, pageCount=100 → 输出:['<', '1', '...', '32', '33', '34', '...', '100']
  • 输入:activePage=2, pageCount=7 → 输出:['<', '1', '2', '3', '...', '7']
  • 输入:activePage=6, pageCount=7 → 输出:['<', '1', '...', '5', '6', '7']
  • 输入:activePage=3, pageCount=6 → 输出:['1', '...', '2', '3', '4', '...', '6']

内容的提问来源于stack exchange,提问作者Miha Šušteršič

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:55:19