美文网首页
封装基于原生js的分页插件

封装基于原生js的分页插件

作者: 无疆wj | 来源:发表于2020-03-18 09:50 被阅读0次

    效果

    分页组件

    1. html

        <!-- css引入 -->
        <link rel="stylesheet" href="./my-page/my-page.css">
        
        <div style="text-align: center;">
            <!-- 所需dom -->
            <div class="my-page"></div>
        </div>
    
        <!--  js -->
        <script src="./my-page/my-page.js"></script>
        <script>
            myPageInit({
                pages: 100,    // 总页数:默认10
                currentPage: 1,   // 当前页码:默认1
                pageStep: 7, // 可显示页码的最多数量,最小7,默认7
                element: '.my-page',    // DOM类名:默认 .my-page
                callback: function (page) {  // 页码改变回调
                    console.log("当前页:", page);
                }
            });
        </script>
    

    2. my-page.css

    .my-page {
      font-size: 14px;
      overflow: hidden;
      margin: 0 auto;
      text-align: center;
      color: #333333;
      display: inline-block;
    }
    
    .my-page .my-page-prev,
    .my-page .my-page-next {
      float: left;
      width: 40px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      border: 1px solid #ddd;
      cursor: pointer;
    }
    
    .my-page .my-page-prev.my-page-forbid,
    .my-page .my-page-next.my-page-forbid {
      pointer-events: none;
      background-color: rgba(0, 0, 0, 0.1);
      color: rgba(0, 0, 0, 0.2);
    }
    
    .my-page .my-page-prev:not(.my-page-forbid):hover,
    .my-page .my-page-next:not(.my-page-forbid):hover {
      border-color: #a02d35;
    }
    
    .my-page .my-page-group {
      float: left;
      margin: 0;
      padding: 0;
      overflow: hidden;
    }
    
    .my-page .my-page-group li {
      float: left;
      list-style: none;
      -webkit-box-sizing: border-box;
              box-sizing: border-box;
      min-width: 40px;
      padding: 0 8px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      margin: 0 5px;
      cursor: pointer;
    }
    
    .my-page .my-page-group .my-page-cell {
      border: 1px solid #ddd;
      border-radius: 2px;
    }
    
    .my-page .my-page-group .my-page-cell:not(.my-page-checked):hover {
      border-color: #a02d35;
      color: #a02d35;
    }
    
    .my-page .my-page-group .my-page-checked {
      border-color: #a02d35;
      background-color: #a02d35;
      color: #ffffff;
    }
    
    .my-page .my-page-group .my-page-omit {
      pointer-events: none;
    }
    /*# sourceMappingURL=my-page.css.map */
    

    3. my-page.js

    function myPageInit({
        pages = 10, // 总页数
        currentPage = 1, // 当前页码
        pageStep = 7, //当前可见最多页码个数,最小值7;默认值7;
        element = '.my-page', // 页面dom类名
        callback
    }) {
    
        intercept(); // 参数校验
    
        // 构造结构
        let htmlStrArr = [];
        for (let i = 0; i < pages; i++) {
            htmlStrArr.push(`<li class="my-page-cell">${i + 1}</li>`);
        };
        if (pages > pageStep) {
            // 在'页面总数'大于'可显示最大页面数'时, 使用 ... 替换 不显示的页码
            let startIndex = pageStep - 2; // 被替换元素的开始索引
            let delNum = htmlStrArr.length - (startIndex - 1); // 替换元素的个数
            htmlStrArr.splice(startIndex, delNum, "<li class='my-page-omit'>...</li>");
        };
        htmlStr = htmlStrArr.join("");
        let pageHtmlStr = `<div class="my-page-prev"><</div>
            <ul class="my-page-group">${htmlStr}</ul>
            <div class="my-page-next">></div>`;
    
        // 注入结构
        const myPageEl = document.querySelector(element);
        myPageEl.innerHTML = pageHtmlStr;
        myPageEl.onclick = function (e) { // 点击事件注册
            // console.log(e)
            let classNameArr = e.target.className.split(" ");
            if (classNameArr.indexOf("my-page-cell") !== -1) {
                clickPageFun(Number(e.target.innerText));
            };
        };
    
        // 标记默认页
        clickPageFun(currentPage);
    
        // 上下页切换事件注册
        let btns = document.querySelectorAll(`${element} div`);
        btns.forEach(el => {
            el.onclick = switchPage;
        });
    
        // 上下页按钮触发
        function switchPage(e) {
            // 获取当前页
            let page = document.querySelector(`${element} .my-page-checked`).innerText - 0;
    
            let classNameArr = e.target.className.split(" ");
            if (classNameArr.indexOf("my-page-prev") !== -1) {
                clickPageFun(page - 1); // 上一页
            } else if (classNameArr.indexOf("my-page-next") !== -1) {
                clickPageFun(page + 1); // 下一页
            };
        };
    
        // 分页切换处理
        function clickPageFun(page) {
            page = Number(page);
            // 满足条件改变结构
            if (pages > pageStep) {
                let newElStr = '';
                let boundaryNum = pageStep - 3; // 边界数
    
                if (page <= boundaryNum) {
                    let str = '';
                    for (let i = 0; i < pageStep - 2; i++) {
                        str += `<li class="my-page-cell">${i+1}</li>`;
                    };
                    newElStr = `${str}
                    <li class="my-page-omit">...</li>
                    <li class="my-page-cell">${pages}</li>`;
    
                } else if (page > boundaryNum && page <= pages - boundaryNum) {
                    let str = '';
                    for (let i = 0; i < pageStep - 4; i++) {
                        str += `<li class="my-page-cell">${page - parseInt((pageStep-4)/2) +i}</li>`;
                    };
                    newElStr = `
                    <li class="my-page-cell">1</li>
                    <li class="my-page-omit">...</li>
                    ${str}
                    <li class="my-page-omit">...</li>
                    <li class="my-page-cell">${pages}</li>`;
    
                } else if (page > pages - boundaryNum) {
                    let str = '';
                    for (let i = pageStep - 2; i > 0; i--) {
                        str += `<li class="my-page-cell">${pages -(i-1)}</li>`;
                    };
    
                    newElStr = `
                    <li class="my-page-cell">1</li>
                    <li class="my-page-omit">...</li>
                    ${str}`;
                };
                document.querySelector(`${element} .my-page-group`).innerHTML = newElStr;
            };
    
            // 标注选中项
            let pageCellELs = document.querySelectorAll(`${element} .my-page-cell`);
            pageCellELs.forEach(el => {
                if (el.innerText == page) {
                    el.classList.add('my-page-checked');
                } else {
                    el.classList.remove('my-page-checked');
                };
            });
    
            forbidden(page); //上下页按钮启禁
            callback && callback(page); // 回调响应
        };
    
        // 上下页按钮启禁
        function forbidden(page) {
            let prveEl = document.querySelector(`${element} .my-page-prev`);
            let nextEl = document.querySelector(`${element} .my-page-next`);
            if (page === 1) {
                prveEl.classList.add('my-page-forbid');
            } else {
                prveEl.classList.remove('my-page-forbid');
            };
    
            if (page === pages) {
                nextEl.classList.add('my-page-forbid');
            } else {
                nextEl.classList.remove('my-page-forbid');
            };
        };
    
        // 参数检验
        function intercept() {
            if (!pages || pages === 0 || (Math.floor(pages) != pages)) {
                throw "my-page中pages必须是整数且不为0";
            };
    
            if (!currentPage || currentPage === 0 || (Math.floor(currentPage) !== currentPage)) {
                throw "my-page中currentPage必须是整数且不为0";
            };
    
            if (!pageStep || pageStep === 0 || (Math.floor(pageStep) !== pageStep) || pageStep < 7) {
                throw "my-page中pageStep必须是整数且不小于7";
            };
    
            if (document.querySelectorAll(element).length === 0) {
                throw element + "元素不存在";
            };
    
            if (currentPage > pages) {
                throw "当前页不存在";
            }
        };
    };
    

    *my-page.scss

    .my-page {
        font-size: 14px;
        overflow: hidden;
        margin: 0 auto;
        text-align: center;
        color: #333333;
        display: inline-block;
    
        // 上下页按钮
        .my-page-prev,
        .my-page-next {
            float: left;
            width: 40px;
            height: 40px;
            line-height: 40px;
            text-align: center;
            border: 1px solid #ddd;
            cursor: pointer;
    
            &.my-page-forbid {
                // cursor: not-allowed;
                pointer-events: none;
                background-color: rgba(0, 0, 0, 0.1);
                color: rgba(0, 0, 0, 0.2);
            }
    
            &:not(.my-page-forbid):hover {
                border-color: #a02d35;
            }
        }
    
        .my-page-group {
            float: left;
            margin: 0;
            padding: 0;
            overflow: hidden;
    
            li {
                float: left;
                list-style: none;
                box-sizing: border-box;
                min-width: 40px;
                padding: 0 8px;
                height: 40px;
                line-height: 40px;
                text-align: center;
                margin: 0 5px;
                cursor: pointer;
            }
    
            .my-page-cell {
                border: 1px solid #ddd;
                border-radius: 2px;
            }
    
            .my-page-cell:not(.my-page-checked):hover {
                border-color: #a02d35;
                color: #a02d35;
            }
    
            .my-page-checked {
                border-color: #a02d35;
                background-color: #a02d35;
                color: #ffffff;
            }
    
            .my-page-omit {
                pointer-events: none;
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:封装基于原生js的分页插件

          本文链接:https://www.haomeiwen.com/subject/bntqyhtx.html