道招

Javascript实现翻页器

如果您发现本文排版有问题,可以先点击下面的链接切换至老版进行查看!!!

Javascript实现翻页器

需求:

写个函数pagination,接收两个参数,第一个是总数,第一个是当前页码,要求当前页码尽可能的在正中间,最多显示5个页码。 比如 pagination(10,4) 就输出 2 3 4 5 6pagination(10,2)就输出 1 2 3 4 5pagination(3,1)就输出 1 2 3

function pagination(total, current = total) {
  if (current > total) current = total;
  if (current < 1) current = 1;
  var res = [current];
  var num = 4,
    step = 0,
    prev = false,
    next = false;
  var i = (j = current);
  while (step < num) {
    if (step < num && j++ < total) {
      step++;
      res.push(j);
    } else {
      next = true;
    }
    if (step < num && i-- > 1) {
      step++;
      res.unshift(i);
    } else {
      prev = true;
    }
    if (prev && next) {
      break;
    }
  }
  return res;
}

体验更好的是在页面很多的情况下中间的用< <或者>>。 代码如下

export const pagination = (totalNum = 5, needEllipsis = true) => (
  total,
  current = total,
) => {
  if (current > total) current = total;
  if (current < 1) current = 1;
  const res = [current];
  totalNum--;
  let step = 0,
    prev = false,
    next = false;
  let i = current;
  let j = current;
  while (step < totalNum) {
    if (step < totalNum && j++ < total) {
      step++;
      res.push(j);
    } else {
      next = true;
    }
    if (step < totalNum && i-- > 1) {
      step++;
      res.unshift(i);
    } else {
      prev = true;
    }
    if (prev && next) {
      break;
    }
  }
  if (needEllipsis) {
    if (res[0] !== 1) {
      if (res[0] - 1 > 1) {
        res.unshift('<<');
      }
      res.unshift(1);
    }
    if (res[res.length - 1] !== total) {
      if (total - res[res.length - 1] > 1) {
        res.push('>>');
      }
      res.push(total);
    }
  }
  return res;
};
更新时间:
上一篇:从vuecli3学习webpack记录(三)基类Tapable和Hook分析下一篇:用个数组来理解vue的diff算法(一)

相关文章

关注道招网公众帐号
友情链接
消息推送
道招网关注互联网,分享IT资讯,前沿科技、编程技术,是否允许文章更新后推送通知消息。
允许
不用了