限制分页中可见页面的数量 [英] Limit the number of visible pages in pagination

查看:17
本文介绍了限制分页中可见页面的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 jQuery 分页工具,当我在进行分页时,我发现了一个缺陷:

一排 14 个以上的分页链接在台式机上很好,但对于移动设备就不行了.所以我想一次将可见页面的数量限制为 5 个(不包括下一个/上一个按钮)并在它到达第三个可见页面时更新它并更新分页中的可见页面,本质上看起来像

<代码>|上一页 |1 |... |3 |4 |5 |6 |下一页 |

我已经写了这个 CodePen 到目前为止我所拥有的.我知道有些插件可以为我执行此操作,但我想避免在此项目中使用插件.

HTML(正在分页的示例内容)

<div class="行内容"><div class="col"><img src="http://via.placeholder.com/350x150">

<div class="col"><img src="http://via.placeholder.com/350x150">

HTML(分页元素)

 

JavaScript:

"使用严格";//注意:类page-item page-link"是在bootstrap 4中使用的类,不会在<li>之外声明或使用.因为引导框架使用这些类来应用 CSS//设置项目数并限制每页项目数var numberOfItems = $("#jar .content").length;var limitPerPage = 2;//由于items从0开始保持每页的items在变量设置的limitPerPage,需要减1,如下图$("#jar .content:gt(" + (limitPerPage - 1) + ")").hide();//设置四舍五入到下一个整数的总页数var totalPages = Math.round(numberOfItems/limitPerPage);//将第1页附加到分页$(".分页").append("<li class='page-item current-page active'><a class='page-link' href='javascript:void(0)'>"+1 +</a></li>");//在上一个按钮之后按顺序附加页面(如codepen中的html所示)for (var i = 2; i <= totalPages; i++) {$(".分页").append("<li class='page-item current-page'><a class='page-link' href='javascript:void(0)'>"+我 +</a></li>");}//附加下一个按钮链接作为分页中的最后一个子元素$(".分页").append("<li class='page-item' id='next-page'><a class='page-link' href='javascript:void(0)'>Next</a></里>");//当一个页面被选中时,如果它有active"类返回false,如果没有active"类,则转到页面并添加active"类属性并从其上具有active"的任何其他元素中删除.$(".pagination li.current-page").on("click", function () {如果 ($(this).hasClass("active")) {返回假;} 别的 {var currentPage = $(this).index();$(".pagination li").removeClass("active");$(this).addClass("active");$("#jar .content").hide();//.hide 将隐藏不适合该页面的内容(即第一页上的 0 和 1,第二页上的 2 和 3 等将显示在适当的页面上)如果它不在该页面的范围内.隐藏,如果它在范围内 .show contentvar GrandTotal = limitPerPage * currentPage;for (var i = grandTotal - limitPerPage; i 

解决方案

我建议使用一个函数——给定当前页码、总页数和你想要的最大按钮数——将返回一个数字数组,其中 0 表示 ... 按钮,其他数字表示可点击的页面按钮.

例如,它可以返回:

[1, 2, 0, 5, 6, 7, 0, 10, 11]

...代表以下按钮:

12...567...1011

该函数将完成计算那些 ... 应该放置的位置的繁重工作,但是一旦你有了它,将它与你的页面集成是小菜一碟.

这是一个示例,它将按钮的数量(不包括 prev/next,包括 ... 按钮)限制为 7.如果您愿意,可以将该参数减少到 5:

//返回一个 maxLength(或更少)页码的数组//其中返回数组中的 0 表示系列中的间隙.//参数://totalPages:总页数//页面:当前页面//maxLength: 返回数组的最大大小函数 getPageList(totalPages, page, maxLength) {if (maxLength <5) throw "maxLength 必须至少为 5";功能范围(开始,结束){return Array.from(Array(end - start + 1), (_, i) => i + start);}var sideWidth = maxLength <9 ?1:2;var leftWidth = (maxLength - sideWidth*2 - 3) >>1;var rightWidth = (maxLength - sideWidth*2 - 2) >>1;如果(总页数 <= maxLength){//列表中没有中断返回范围(1,总页数);}if (page <= maxLength - sideWidth - 1 - rightWidth) {//页面左侧没有中断返回范围(1,maxLength - sideWidth - 1).concat(0, range(totalPages - sideWidth + 1, totalPages));}if (page >= totalPages - sideWidth - 1 - rightWidth) {//页面右侧没有中断返回范围(1,边宽).concat(0, range(totalPages - sideWidth - 1 - rightWidth - leftWidth, totalPages));}//两边断点返回范围(1,边宽).concat(0, range(page - leftWidth, page + rightWidth),0, range(totalPages - sideWidth + 1, totalPages));}//下面是上述函数的使用示例.$(函数(){//项目数并限制每页的项目数var numberOfItems = $("#jar .content").length;var limitPerPage = 2;//向上舍入的总页数var totalPages = Math.ceil(numberOfItems/limitPerPage);//顶部按钮的数量,不计算上一个/下一个,//但包括虚线按钮.//必须至少为 5:var paginationSize = 7;var currentPage;功能 showPage(whichPage) {if (whichPage < 1 || whichPage > totalPages) 返回 false;currentPage = whichPage;$("#jar .content").hide().slice((currentPage-1) * limitPerPage,currentPage * limitPerPage).show();//替换导航项(不是上一个/下一个):$(".pagination li").slice(1, -1).remove();getPageList(totalPages, currentPage, paginationSize).forEach( item => {$("
  • ").addClass("page-item").addClass(项目?当前页面":已禁用").toggleClass("active", item === currentPage).append($("").addClass("page-link").attr({href: "javascript:void(0)"}).text(item || "...")).insertBefore("#next-page");});//在第一页/最后一页时禁用上一页/下一页:$("#previous-page").toggleClass("disabled", currentPage === 1);$("#next-page").toggleClass("disabled", currentPage === totalPages);返回真;}//包括上一个/下一个按钮:$(".分页").append($("
  • ").addClass("page-item").attr({ id: "previous-page" }).append($("").addClass("page-link").attr({href: "javascript:void(0)"}).text("Prev")),$("
  • ").addClass("page-item").attr({ id: "next-page" }).append($("").addClass("page-link").attr({href: "javascript:void(0)"}).text("Next")));//显示页面链接$("#jar").show();显示页面(1);//使用事件委托,因为这些项目稍后会重新创建$(document).on("click", ".pagination li.current-page:not(.active)", function () {return showPage(+$(this).text());});$("#next-page").on("click", function () {返回 showPage(currentPage+1);});$("#previous-page").on("click", function () {返回 showPage(currentPage-1);});});
  • <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="样式表"><div class="分页">

    <div id="jar" style="display:none"><div class="content">1) Lorem ipsum dolor sat amet, consectetur adipiscing elit.</div><div class="content">2) Maecenas vitae elit arcu.</div><div class="content">3) Pellentesque sagittis risus ac ante ultricies,ac convallis urna elementum.</div><div class="content">4) Vivamus sodales aliquam massa quis lobortis.

    <div class="content">5) Phasellus id sem sollicitudin lacus condimentummalesuada vel tincidunt neque.</div><div class="content">6) Donec magna leo、rhoncus quis nunc eu、malesuada consectetur orci.</div><div class="content">7) Praesent sollicitudin, quam a ullamcorper pharetra, urna lacus mollis sem, quis semper augue massa ac est.</div><div class="content">8) Etiam leo magna、fermentum quis quam non、aliquam tincidunt erat.</div><div class="content">9) Morbi pellentesque nibh nec nibh posuere, vel tempor magna dignissim.</div><div class="content">10) 在最大发酵元素中.Vestibulum ac lectus pretium, suscipit ante nec, bibendum erat.</div><div class="content">11) Phasellus 坐在 amet orci 植物丛中.Etiam faucibus scelerisque purus.</div><div class="content">12) Pellentesque laoreet ipsum ac laoreet consectetur.

    <div class="content">13) 整数 aliquet odio magna, lobortis mattis Tortor suscipit sed.</div><div class="content">14) 类 aptent taciti socialsqu ad litora Tornt per conubia nostra, per inceptos himenaeos.

    <div class="content">15) Mauris atellus luctus turpis elementum imperdiet vitaemalesuada mauris.

    <div class="content">16) Donec id libero sagittis, laoreet lorem vel, tempus nunc.

    <div class="content">17) Donec vitae neque sed ex tristique hendrerit.</div><div class="content">18) Aliquam sollicitudin gravida varius.</div><div class="content">19) Donec auctor, augue sed finibusfermentum, neque erat interdum libero, eget porta metus lectus quis odio.</div><div class="content">20) Nunc quis ante enim.Etiam nisl orci,hendrerit ut pretium nec,tempor in metus.</div><div class="content">21) Donec et semper arcu.</div><div class="content">22) Donec lobortis interdum purus, eu semper nisl pulvinar ac.</div><div class="content">23) Cras laoreet eu elit vel porta.</div><div class="content">24) Quisque pharetra arcu eget diam posuere commodo.</div><div class="content">25) Nulla ornare eleifend neque,eget tincidunt nunc ullamcorper id.</div>

    I'm working on a jQuery pagination tool, and while I have the pagination working, I see a flaw:

    Having a row of 14+ pagination links is fine on a desktop, but it is not OK for a mobile device. So I want to limit the number of visible pages to 5 at a time (not including the next/prev buttons) and have it update when it reaches the third visible page and update the visible pages in the pagination essentially looking like

    | Prev | 1 | ... | 3 | 4 | 5 | 6 | Next |
    

    I've written this CodePen of what I have so far. I'm aware there are plug-ins that do this for me but I want to avoid using plug-ins for this project.

    HTML (example content being paginated)

    <div class="container" id="jar">
        <div class="row content">
             <div class="col">
                  <img src="http://via.placeholder.com/350x150">
             </div>
             <div class="col">
                 <img src="http://via.placeholder.com/350x150">
             </div>
        </div>
    </div>
    

    HTML (pagination element)

     <nav>
       <ul class="pagination justify-content-center pagination-sm">
         <li id="previous-page" class="page-item"><a class="page-link" href="javascript:void(0)">Prev</a>
         </li>
       </ul>
     </nav>
    

    JavaScript:

    "use strict";
     //NOTE: the class"page-item page-link" are classes used in bootstrap 4 and will not be seen declared or used outside of the <li> as the bootstrap framework uses those classes to apply CSS
    
     //sets number of items and limits the number of items per page
    
    var numberOfItems = $("#jar .content").length;
    var limitPerPage = 2;
    
    //as the items start at 0 to keep the items per page at the limitPerPage set in variable, need to subtract 1 as is shown below
    
    $("#jar .content:gt(" + (limitPerPage - 1) + ")").hide();
    
    //sets total pages rounded to the next whole number
    
    var totalPages = Math.round(numberOfItems / limitPerPage);
    
    //append the 1 page to the pagination
    
    $(".pagination").append(
            "<li class='page-item current-page active'><a class='page-link'  href='javascript:void(0)'>" +
            1 +
            "</a></li>"
            );
    
    //append the pages in sequential order after prev button (as seen in the html in codepen)
    
    for (var i = 2; i <= totalPages; i++) {
        $(".pagination").append(
                "<li class='page-item current-page'><a class='page-link' href='javascript:void(0)'>" +
                i +
                "</a></li>"
                );
    }
    
    //appends the next button link as the final child element in the pagination
    
    $(".pagination").append(
            "<li class='page-item' id='next-page'><a class='page-link' href='javascript:void(0)'>Next</a></li>"
            );
    
    //When a page is selected, if it has "active" class return false, if no "active" class, go to page and add "active" class attribute and remove from any other element that has "active" on it.
    
    $(".pagination li.current-page").on("click", function () {
        if ($(this).hasClass("active")) {
            return false;
        } else {
            var currentPage = $(this).index();
            $(".pagination li").removeClass("active");
            $(this).addClass("active");
            $("#jar .content").hide();
    
           //.hide will hide content that does not fit into that page (ie 0 and 1 on page one, 2 and 3 on page two and so on will show on appropriate page)  If it does not fall within the range for that page .hide, if it falls within the range .show content
    
            var grandTotal = limitPerPage * currentPage;
    
            for (var i = grandTotal - limitPerPage; i < grandTotal; i++) {
                $("#jar .content:eq(" + i + ")").show();
            }
        }
    });
    
    //when next is clicked if it is on the last page, return false otherwise move on to next page in pagination and remove "active" class from previous page and add "active" class to new page
    
    $("#next-page").on("click", function () {
        var currentPage = $(".pagination li.active").index();
        if (currentPage === totalPages) {
            return false;
        } else {
            currentPage++;
            $(".pagination li").removeClass("active");
            $("#jar .content").hide();
    
            var grandTotal = limitPerPage * currentPage;
    
            for (var i = grandTotal - limitPerPage; i < grandTotal; i++) {
                $("#jar .content:eq(" + i + ")").show();
            }
            $(".pagination li.current-page:eq(" + (currentPage - 1) + ")").addClass(
                    "active"
                    );
        }
    });
    
    //when prev is clicked if it is on the 1 page, return false otherwise move on to previous page and remove "active" class from last page visited and add "active" class to new page
    
    $("#previous-page").on("click", function () {
        var currentPage = $(".pagination li.active").index();
        if (currentPage === 1) {
            return false;
        } else {
            currentPage--;
            $(".pagination li").removeClass("active");
            $("#jar .content").hide();
    
            var grandTotal = limitPerPage * currentPage;
    
            for (var i = grandTotal - limitPerPage; i < grandTotal; i++) {
                $("#jar .content:eq(" + i + ")").show();
            }
            $(".pagination li.current-page:eq(" + (currentPage - 1) + ")").addClass(
                    "active"
                    );
        }
    });
    

    解决方案

    I would suggest using a function that -- given a current page number, the total number of pages, and the maximum number of buttons you want to have -- will return an array of numbers, where 0 denotes a ... button, and other numbers denote clickable page buttons.

    So for example, it could return:

    [1, 2, 0, 5, 6, 7, 0, 10, 11]
    

    ...which would represent the following buttons:

    1, 2, ..., 5, 6, 7, ..., 10, 11

    That function will do the hard work of calculating where those ... should be placed, but once you have that, it is a piece of cake to integrate it with your page.

    Here is an example that will limit the number of buttons (excluding prev/next, including ... buttons) to 7. You can reduce that parameter to 5 if you like:

    // Returns an array of maxLength (or less) page numbers
    // where a 0 in the returned array denotes a gap in the series.
    // Parameters:
    //   totalPages:     total number of pages
    //   page:           current page
    //   maxLength:      maximum size of returned array
    function getPageList(totalPages, page, maxLength) {
        if (maxLength < 5) throw "maxLength must be at least 5";
    
        function range(start, end) {
            return Array.from(Array(end - start + 1), (_, i) => i + start); 
        }
    
        var sideWidth = maxLength < 9 ? 1 : 2;
        var leftWidth = (maxLength - sideWidth*2 - 3) >> 1;
        var rightWidth = (maxLength - sideWidth*2 - 2) >> 1;
        if (totalPages <= maxLength) {
            // no breaks in list
            return range(1, totalPages);
        }
        if (page <= maxLength - sideWidth - 1 - rightWidth) {
            // no break on left of page
            return range(1, maxLength - sideWidth - 1)
                .concat(0, range(totalPages - sideWidth + 1, totalPages));
        }
        if (page >= totalPages - sideWidth - 1 - rightWidth) {
            // no break on right of page
            return range(1, sideWidth)
                .concat(0, range(totalPages - sideWidth - 1 - rightWidth - leftWidth, totalPages));
        }
        // Breaks on both sides
        return range(1, sideWidth)
            .concat(0, range(page - leftWidth, page + rightWidth),
                    0, range(totalPages - sideWidth + 1, totalPages));
    }
    
    // Below is an example use of the above function.
    $(function () {
        // Number of items and limits the number of items per page
        var numberOfItems = $("#jar .content").length;
        var limitPerPage = 2;
        // Total pages rounded upwards
        var totalPages = Math.ceil(numberOfItems / limitPerPage);
        // Number of buttons at the top, not counting prev/next,
        // but including the dotted buttons.
        // Must be at least 5:
        var paginationSize = 7; 
        var currentPage;
    
        function showPage(whichPage) {
            if (whichPage < 1 || whichPage > totalPages) return false;
            currentPage = whichPage;
            $("#jar .content").hide()
                .slice((currentPage-1) * limitPerPage, 
                        currentPage * limitPerPage).show();
            // Replace the navigation items (not prev/next):            
            $(".pagination li").slice(1, -1).remove();
            getPageList(totalPages, currentPage, paginationSize).forEach( item => {
                $("<li>").addClass("page-item")
                         .addClass(item ? "current-page" : "disabled")
                         .toggleClass("active", item === currentPage).append(
                    $("<a>").addClass("page-link").attr({
                        href: "javascript:void(0)"}).text(item || "...")
                ).insertBefore("#next-page");
            });
            // Disable prev/next when at first/last page:
            $("#previous-page").toggleClass("disabled", currentPage === 1);
            $("#next-page").toggleClass("disabled", currentPage === totalPages);
            return true;
        }
    
        // Include the prev/next buttons:
        $(".pagination").append(
            $("<li>").addClass("page-item").attr({ id: "previous-page" }).append(
                $("<a>").addClass("page-link").attr({
                    href: "javascript:void(0)"}).text("Prev")
            ),
            $("<li>").addClass("page-item").attr({ id: "next-page" }).append(
                $("<a>").addClass("page-link").attr({
                    href: "javascript:void(0)"}).text("Next")
            )
        );
        // Show the page links
        $("#jar").show();
        showPage(1);
    
        // Use event delegation, as these items are recreated later    
        $(document).on("click", ".pagination li.current-page:not(.active)", function () {
            return showPage(+$(this).text());
        });
        $("#next-page").on("click", function () {
            return showPage(currentPage+1);
        });
    
        $("#previous-page").on("click", function () {
            return showPage(currentPage-1);
        });
    });

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    
    <div class="pagination">
    </div>
    
    <div id="jar" style="display:none">
        <div class="content">1) Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
        <div class="content">2) Maecenas vitae elit arcu.</div>
        <div class="content">3) Pellentesque sagittis risus ac ante ultricies, ac convallis urna elementum.</div>
        <div class="content">4) Vivamus sodales aliquam massa quis lobortis. </div>
        <div class="content">5) Phasellus id sem sollicitudin lacus condimentum malesuada vel tincidunt neque.</div>
        <div class="content">6) Donec magna leo, rhoncus quis nunc eu, malesuada consectetur orci.</div>
        <div class="content">7) Praesent sollicitudin, quam a ullamcorper pharetra, urna lacus mollis sem, quis semper augue massa ac est.</div>
        <div class="content">8) Etiam leo magna, fermentum quis quam non, aliquam tincidunt erat.</div>
        <div class="content">9) Morbi pellentesque nibh nec nibh posuere, vel tempor magna dignissim.</div>
        <div class="content">10) In maximus fermentum elementum. Vestibulum ac lectus pretium, suscipit ante nec, bibendum erat.</div>
        <div class="content">11) Phasellus sit amet orci at lectus fermentum congue. Etiam faucibus scelerisque purus.</div>
        <div class="content">12) Pellentesque laoreet ipsum ac laoreet consectetur. </div>
        <div class="content">13) Integer aliquet odio magna, lobortis mattis tortor suscipit sed.</div>
        <div class="content">14) Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </div>
        <div class="content">15) Mauris a tellus luctus turpis elementum imperdiet vitae malesuada mauris. </div>
        <div class="content">16) Donec id libero sagittis, laoreet lorem vel, tempus nunc. </div>
        <div class="content">17) Donec vitae neque sed ex tristique hendrerit.</div>
        <div class="content">18) Aliquam sollicitudin gravida varius.</div>
        <div class="content">19) Donec auctor, augue sed finibus fermentum, neque erat interdum libero, eget porta metus lectus quis odio.</div>
        <div class="content">20) Nunc quis ante enim. Etiam nisl orci, hendrerit ut pretium nec, tempor in metus.</div>
        <div class="content">21) Donec et semper arcu.</div>
        <div class="content">22) Donec lobortis interdum purus, eu semper nisl pulvinar ac.</div>
        <div class="content">23) Cras laoreet eu elit vel porta.</div>
        <div class="content">24) Quisque pharetra arcu eget diam posuere commodo.</div>
        <div class="content">25) Nulla ornare eleifend neque, eget tincidunt nunc ullamcorper id. Nulla facilisi.</div>
    </div>

    这篇关于限制分页中可见页面的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆