lishengzxc / bblog

My Blog
https://github.com/lishengzxc/bblog/issues
178 stars 8 forks source link

超简单的分页 #19

Open lishengzxc opened 7 years ago

lishengzxc commented 7 years ago
  function showPages(page, total) {
    var result = [page];
    for (var i = 1; i <= 3; i++) {
      if (page - i > 1) {
        result.unshift(page - i)
      }

      if (page + i < total) {
        result.push(page + i);
      }
    }

    if (page - 4 > 1) {
      result = ['...'].concat(result)
    }

    if (page > 1) {
      result = ['上一页', 1].concat(result)
    }

    if (page + 4 < total) {
      result.push('...');
    }

    if (page < total) {
      result = result.concat([total, '下一页'])
    }

    return result.join(' ');
  }

  // test
  var total = 110;  
  for (var i = 1; i <= total; i++) {  
    var ret = showPages(i, total);
    console.log(`${i}:`, ret);
  }