效果如下:
    image.png

    代码如下:

    1. <!DOCTYPE html>
    2. <html lang="zh">
    3. <head>
    4. <meta charset="UTF-8" />
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    6. <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    7. <title>Document</title>
    8. </head>
    9. <body>
    10. <span id="pagingText"></span>页,共<span id="total">40</span>
    11. <div id="pagingDiv"></div>
    12. </body>
    13. <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
    14. <script>
    15. var total = $('#total').html();
    16. //一进页面默认第1页
    17. pagingConstruct(1);
    18. //点击页数
    19. $("#pagingDiv").on('click','a',function(){
    20. var text = $(this).html();
    21. pagingConstruct(parseInt(text));
    22. })
    23. function pagingConstruct(paging){
    24. $('#pagingText').html(paging)
    25. var pagingDivInnerHTML = "";
    26. var isHiddenExist = 0;//这里是加载省略号的flag
    27. //从第1页读到第40页。
    28. for (var i = 1; i <= total; i++) {
    29. if (i == paging) {//如果读到当前页,就仅仅加载一个文本,不放a链接
    30. pagingDivInnerHTML += i + " ";
    31. }else {
    32. //如果是页首,中间页,页尾,当前页的前后三页则不省略。
    33. if (i < 4 || i < (paging + 3) && i > (paging - 3) || i > (total / 2 - 2) && i < (total / 2 + 2) || i > (total - 3)) {
    34. pagingDivInnerHTML += "<a href='javascript:void(0)' >" + i + "</a> ";
    35. isHiddenExist = 0;
    36. }else {//否则就构造...
    37. if (isHiddenExist == 0) {
    38. pagingDivInnerHTML += "...";
    39. isHiddenExist = 1;
    40. }
    41. }
    42. }
    43. }
    44. //把构造的内容放上去pagingDiv
    45. $("#pagingDiv").html(pagingDivInnerHTML);
    46. }
    47. </script>
    48. </html>