分享一个纯JS编写的分页工具


> 最近在阅读公司项目代码的时候, 发现分页部分看不懂了, 当时我就想

>

> 最近在工作中遇到一些分页相关的问题, 对于别人封装好的又不咋会用, 于是 , 就突发奇想, 想写一个属于自己专属的分页工具, 满足一下需求:

>

> * 用纯js编写

> *  无依赖, 方便嵌入项目

>

> *  最好能用到面向对象的知识

>

> 综上想法, 于是, 一个使用面向对象思想编写的纯s分页就出现了

>

> 如果有想用的朋友可以拿去用, 记得多多留下宝贵意见, 感激不尽, 对了 ,代码是纯js编写. 使用到了es6语法,所以 不支持试es6语法的浏览器理论应该跑不起来

## 工具源码

```js

/**

 * 分页参数配置对象,用于配置分页参数信息

 */

 class AttrConf{

    /**

     * 分页基本属性

     */

    curPage = 1;

    limit = 10;

    limits = [10,20,30,50,100];

    dataTotal = 0;

    pageTotal = 0;

    pageBox = {

        items:7,

        pages:[],

    }

    rowNo = {

        start:1,

        end:1

    }

    /**

     * 分页配置构造器

     * @param {*} curPage 当前页

     * @param {*} limit 每页显示条数

     * @param {*} dataTotal 总数据条数

     */

    constructor(curPage,limit,dataTotal){

        this.init({curPage,limit,dataTotal});

    }

    init(param){

        if(param.curPage){

            this.setCurPage(param.curPage);

        }

        if(param.limit){

            this.setLimit(param.limit);

        }

        if(param.dataTotal){

            this.setDataTotal(param.dataTotal);

        }

        this.initOthers();

    }

    /**

     * 初始化分页配置项其他属性

     */

    initOthers(){

        //初始化总页数

        if(this.dataTotal>0){

            this.pageTotal = parseInt(this.dataTotal / this.limit) + (this.dataTotal % this.limit == 0 ? 0 : 1);

            //确保当前页始终在总页数限制范围内

            if(this.curPage > this.pageTotal){

                this.curPage = this.pageTotal;

            }

        }

        //初始化当前页显示数据索引

        if(this.dataTotal <= this.limit){

            this.rowNo.start = 1;

            this.rowNo.end = this.dataTotal;

        }else if(this.curPage == this.pageTotal){

            this.rowNo.start = (this.curPage - 1) * this.limit + 1;

            this.rowNo.end = this.dataTotal;

        }else{

            this.rowNo.start = (this.curPage - 1) * this.limit + 1;

            this.rowNo.end = this.rowNo.start + this.limit - 1;

        }

        //初始化页码总数

        this.setPageCodes();

    }

    /**

     * 设置当前页

     * @param {Number} curPage 当前页

     * @param {Boolean} reloadOthers 是否初始化其他属性 默认不初始化

     */

    setCurPage(curPage,reloadOthers){

        this.curPage = curPage;

        if(reloadOthers == true){

            this.initOthers();

        }

    }

    /**

     * 设置每页显示条数

     * @param {Number} limit  每页条数

     * @param {Boolean} reloadOthers 是否初始化其他属性 默认不初始化

     */

    setLimit(limit,reloadOthers){

        this.limit = limit;

        if(reloadOthers == true){

            this.initOthers();

        }

    }


    /**

     * 设置总数据条数

     * @param {Number} dataTotal  总数据条数

     * @param {Boolean} reloadOthers 是否初始化其他属性 默认不初始化

     */

     setDataTotal(dataTotal,reloadOthers){

        this.dataTotal = dataTotal;

        if(reloadOthers == true){

            this.initOthers();

        }

    }

    /**

     * 设置当前页显示的可快捷跳转的页码个数 如 2,3,4,5,6

     */

    setPageCodes(){

        this.pageBox.pages = [];

        if(this.pageTotal <= this.pageBox.items){

            for(let i = 1; i <= this.pageTotal; i++){

                this.pageBox.pages.push(i);

            }

            return ;

        }

        //总页数大于配置的要显示的总页码数, 比如 总页数是10 ,配置的是每页显示6个页码

        //得到以当前页为中心向左右便宜的偏移量 向下取整

        let offset = Math.floor(this.pageBox.items / 2);

        this.pageBox.pages.push(this.curPage);

        let pagesLen = this.pageBox.pages.length;

        let skipL = 0,skipR = 0;

        for(let i = 1; i <= offset; i++){

            let maxPage = this.curPage + i;

            let minPage = this.curPage - i;

            //每循环一次,检测一次当前总页码项数,只有总页码项数小于配置项才添加

            if(pagesLen < this.pageBox.items){

                //往右边添加页码

                if(minPage >= 1){

                    this.pageBox.pages.unshift(minPage);

                    //从新计算总页码相熟 方便下次循环参考

                    pagesLen += 1;

                }else{

                    skipR += 1;

                }

            }


            if(pagesLen < this.pageBox.items){

                //往左边添加页码

                if(maxPage <= this.pageTotal){

                    this.pageBox.pages.push(maxPage);

                    //从新计算总页码相熟 方便下次循环参考

                    pagesLen += 1;

                }else{

                    skipL += 1;

                }

            }

        }

        //处理总页码数不满足配置项的情况

        if(skipL > 0 ){

            //说明需要向左边补充skipL个盒子

            for(let i = 1; i <= skipL; i++){

                let startPage = this.pageBox.pages[0];

                if(pagesLen < this.pageBox.items){

                    this.pageBox.pages.unshift(startPage - 1);

                    //从新计算总页码相熟 方便下次循环参考

                    pagesLen += 1;

                }

            }

        }

        if(skipR > 0 ){

            //说明需要向左边补充skipL个盒子

            for(let i = 1; i <= skipR; i++){

                let endPage = this.pageBox.pages[pagesLen-1];

                if(pagesLen < this.pageBox.items){

                    this.pageBox.pages.push(endPage + 1);

                    //从新计算总页码相熟 方便下次循环参考

                    pagesLen += 1;

                }

            }

        }

    }

}

/**

 * 分页视图配置对象,用于根据分页参数创建dom元素

 */

class ViewConf{

    AttrConf;

    /**

     * 分页视图对象 分为左右两大区域,当左侧隐藏,右侧自动填充

     *   左侧区域 可以显示或关闭

     *      基本信息(base)

     *   右侧区域 以下视图模块可任意组合

     *      上一页(prev),下一页(next),页码区(pages),每页显示条数(limits),快速跳转(jump)

     */

    layout = {

        unit: '%',

        main: null,

        left:{

            show: true,

            width: 27,

            ids: ['base'],

            dom:null,

            modules: {},

        },

        right:{

            width: 100,

            ids: ['prev','pages','next','limits','jump'],

            dom:null,

            modules:{}

        }

    };

    modules = {

        pages:[]

    };

    // 分页按钮颜色主题配置

    theme = {

        deault:{

            pageBtn:{border:"#e1f5fe",boxShadow:"#c4d8e0"},

            pageBtnCur:{border:"#e1f5fe",color:"#8BC34A",boxShadow:"#c4d8e0",backgroundColor:"#e1f5fe"},

            pageBtnDisabled:{border:"#e1f5fe",color:"#636262",boxShadow:"#ddf2fb"},

        }

    }

    //默认 基本样式

    cssMap = {

        base:{//分页信息样式

            fontSize:  "13px",

            color:  "rgb(58, 63, 66)",

        },

        pageBtn:{ //按钮基本样式

            border:  "1px solid #ccc",

            padding:  "3px 5px",

            borderRadius:  "3px",

            display:  "inline-block",

            fontSize:  "13px",

            margin:  "0 2px",

            boxShadow:  "inset 0px 0px 3px 1px #c7c2c2",

            height:  "20px",

            color:  "rgb(58, 63, 66)",

            lineHeight:  "20px",

            minWidth:  "30px",

            textAlign:  "center",

            cursor:  "pointer",

            textDecoration: "unset"

        },

        pageBtnHover:{//鼠标经过按钮样式

            boxShadow: "inset 0px 0px 4px 2px #c7c2c2",

            color:"unset"

        },

        pageBtnPressDown:{//按钮按下样式

            color:"darkorange",

            boxShadow: "inset 0px 0px 5px 3px #c7c2c2",

            fontWeight: "bolder",

        },

        pageBtnCur:{ //当前页按钮样式

            boxShadow: "#81D4FA 0px 0px 3px 1px inset",

            color:"#009688",

            fontWeight: "bolder",

            cursor: "not-allowed",

            border: "1px solid #E1F5FE",

            backgroundColor:"#E1F5FE"

        },

        pageBtnDisabled:{//按钮禁用样式

            border: "1px solid #efefef",

            boxShadow: "#efefef 0px 0px 3px 1px inset",

            color: "#efefef",

            cursor: "not-allowed",

        }

    }

    /**

     * 分页视图对象构造器

     * @param {AttrConf} AttrConf 对象

     */

    constructor(AttrConf,theme){

        this.AttrConf = AttrConf;


        this.initTheme(theme);

        this.initLayout();

        this.initModuls();

    }

    /**

     * 设置主题样式

     * @param {*} theme

     */

    initTheme(theme){

        if(!theme)

            theme = "default";

        let themeConf = this.theme[theme];

        if(!themeConf)

            themeConf = this.theme.deault;

        for(let key in this.cssMap){

            switch(key){

                case "pageBtn":

                    this.cssMap.pageBtn.border = "1px solid " + themeConf.pageBtn.border;

                    this.cssMap.pageBtn.boxShadow = "inset 0px 0px 3px 1px " + themeConf.pageBtn.boxShadow;

                    this.cssMap.pageBtnHover.boxShadow = "inset 0px 0px 5px 1px " + themeConf.pageBtn.boxShadow;

                    this.cssMap.pageBtnPressDown.boxShadow = "inset 0px 0px 7px 2px " + themeConf.pageBtn.boxShadow;

                    break;

                case "pageBtnCur":

                    this.cssMap.pageBtnCur.border = "1px solid " + themeConf.pageBtnCur.border;

                    this.cssMap.pageBtnCur.boxShadow = "inset 0px 0px 3px 1px " + themeConf.pageBtnCur.boxShadow;

                    this.cssMap.pageBtnCur.color = themeConf.pageBtnCur.color;

                    this.cssMap.pageBtnCur.backgroundColor = themeConf.pageBtnCur.backgroundColor;

                    break;

                case "pageBtnDisabled":

                    this.cssMap.pageBtnDisabled.border = "1px solid " + themeConf.pageBtnDisabled.border;

                    this.cssMap.pageBtnDisabled.boxShadow = "inset 0px 0px 3px 1px " + themeConf.pageBtnDisabled.boxShadow;

                    this.cssMap.pageBtnDisabled.color = themeConf.pageBtnDisabled.color;

                    break;

            }

        }

    }


    /**

     * 初始化视图布局

     */

    initLayout(){

        this.layout.main = this.createElem('div',{layout:'main'},null);

        //重置右布局宽度

        let ids = null;

        let inst = this;

        if(inst.layout.left.show){

            inst.layout.right.width =-  inst.layout.left.width;

            //创建左布局容器

            inst.layout.left.dom

                = inst.createElem('div',{layout:'left'},{width: inst.layout.left.width+inst.layout.unit});

            //添加模块

            ids = inst.layout.left.ids;

            ids.forEach(domId => inst.layout.left.modules[domId]

                = inst.createElem('div',{module:domId},{}));

        }

        //创建右布局容器

        inst.layout.right.dom

                = inst.createElem('div',{layout:'right'},{width: inst.layout.right.width+inst.layout.unit});

        //添加模块

        ids = inst.layout.right.ids;

        ids.forEach(domId => inst.layout.right.modules[domId]

            = inst.createElem('span',{module:domId},{}));

    }

    setLayout(layout){

        if(layout.left){

            if(layout.left.show){

                this.layout.left.show = layout.left.show;

            }

            if(layout.left.modules){

                this.layout.left.ids = layout.left.modules;

            }

        }

        if(layout.right){

            if(layout.right.modules){

                this.layout.right.ids = layout.right.modules;

            }

        }

        this.initLayout();

        this.initModuls();

    }

    /**

     * 初始化模型,根据视图下的模型个数确定

     */

    initModuls(){


        let modules = [];

        let inst = this;

        if(this.layout.left.show){

            this.layout.left.ids.forEach(mode => modules.push(mode));

        }

        this.layout.right.ids.forEach(mode => modules.push(mode));

        modules.forEach(module => {

            let fnName = 'load' + module.substring(0,1).toUpperCase() + module.substring(1);

            try{

                inst[fnName](true);

            }catch(e){

                console.warn("模块错误,未知的模块名:"+module)

            }

        })

    }

    loadBase(){

        if(!this.modules.base){

            let baseDom = this.createElem('div',{module:"base"});

            baseDom.innerHTML = `

                <div>

                    <small>当前显示第 <b><start>`+this.AttrConf.rowNo.start+`</start><i>~</i><end>`+this.AttrConf.rowNo.end+`</end></b> 条</small>

                </div>

                <div>

                    <small>第 <b><cur-page>`+this.AttrConf.curPage+`</cur-page><i>/</i><total-page>`+this.AttrConf.pageTotal+`</total-page></b> 页</small>

                    <small>共 <b><total-data>`+this.AttrConf.dataTotal+`</total-data></b> 条记录</small>  

                </div>`;

            this.modules.base = baseDom;

        }

        let baseDom = this.modules.base;

        baseDom.querySelector("start").innerHTML = this.AttrConf.rowNo.start;

        baseDom.querySelector("end").innerHTML = this.AttrConf.rowNo.end;

        baseDom.querySelector("cur-page").innerHTML = this.AttrConf.curPage;

        baseDom.querySelector("total-page").innerHTML = this.AttrConf.pageTotal;

        baseDom.querySelector("total-data").innerHTML = this.AttrConf.dataTotal;

    }

    /**

     * 加载分页页码

     */

    loadPages(isInit){

        if(isInit == true){

            //初始化

            this.modules.pages = [];

            for(let i = 0;i < this.AttrConf.pageBox.pages.length; i++){

                this.modules.pages.push(this.createElem('a',{href:"#",btn:"code",module:"pages"},this.cssMap.pageBtn));

            }


        }

        //修改属性

        for(let i = 0;i < this.AttrConf.pageBox.items; i++){

            let code = this.AttrConf.pageBox.pages[i];

            let page = this.modules.pages[i];

            page.innerHTML = code;


            let attrMap = {

                pagecode: code,

            };

            if(code == this.AttrConf.curPage){

                attrMap.active = "";

                attrMap.disabled = "";

            }

            this.attr(page,attrMap);

        }

        let offset = Math.floor(this.AttrConf.pageBox.items / 2);


        if((this.AttrConf.curPage - offset) > 1){

            let first = this.createElemBase('a',1);

            this.attr(first,{

                pagecode: 1,

                href:"#",

                btn:"code"

            });

            let lblL = this.createElemBase('a','...');

            this.attr(lblL,{

                disabled : "",

                href:"#",

                btn:""

            });


            this.css(first,this.cssMap.pageBtn);

            this.css(lblL,this.cssMap.pageBtn);

            this.modules.pages.unshift(lblL);

            this.modules.pages.unshift(first);

        }

        if((this.AttrConf.curPage + offset) < this.AttrConf.pageTotal){

            let last = this.createElemBase('a',this.AttrConf.pageTotal);

            this.attr(last,{

                pagecode: this.AttrConf.pageTotal,

                href:"#",

                btn:"code"

            });

            let lblR = this.createElemBase('a','...');

            this.attr(lblR,{

                disabled : "",

                href:"#",

                btn:""

            });


            this.css(last,this.cssMap.pageBtn);

            this.css(lblR,this.cssMap.pageBtn);

            this.modules.pages.push(lblR);

            this.modules.pages.push(last);

        }

    }

    /**

     * 加载上一页

     * @param {Boolean} isInit

     */

    loadPrev(isInit){

        if(isInit){

            this.modules.prev = this.createElem('a',{href:"#",btn:"code",module:"prev"},this.cssMap.pageBtn,'上一页');

        }

        // 设置按钮状态

        let attrMap = {

            pagecode: this.AttrConf.curPage - 1

        }

        if(this.AttrConf.curPage <= 1){

            attrMap.disabled = ""

        }

        this.attr(this.modules.prev,attrMap);

    }

    /**

     * 加载下一页

     * @param {Boolean} isInit

     */

    loadNext(isInit){

        if(isInit){

            this.modules.next = this.createElem('a',{href:"#",btn:"code",module:"next"},this.cssMap.pageBtn,'下一页');

        }

        // 设置按钮状态

        let attrMap = {

            pagecode: this.AttrConf.curPage + 1

        }

        if(this.AttrConf.curPage >= this.AttrConf.pageTotal){

            attrMap.disabled = ""

        }

        this.attr(this.modules.next,attrMap);

    }

    /**

     * 加载快捷跳页

     * @param {Boolean} isInit

     */

    loadJump(isInit){

        if(isInit){

            let jump = this.createElem("span",{module:"jump"},this.cssMap.pageBtn,null);

            let jumpInput = this.createElem('input',{

                type: "text",

                maxlength: (this.AttrConf.pageTotal+"").length,

                value: this.AttrConf.curPage

            },{

                width: ((this.AttrConf.pageTotal+"").length * 11) + "px",

                textAlign: 'center',

                fontWeight: 'bolder',

                fontSize: '14px',

                border: "unset",

            },null);

            let jumpGo = this.createElem("a",{href:"#"},{},'Go');

            jump.appendChild(this.createElemBase("span","到第"));

            jump.appendChild(jumpInput);

            jump.appendChild(this.createElemBase("span","<b>/ "+this.AttrConf.pageTotal+"</b>页 "));

            jump.appendChild(jumpGo);

            this.modules.jump = jump;

        }

    }

    /**

     * 加载每页显示控制

     * @param {Boolean} isInit

     */

     loadLimits(isInit){

        if(isInit){

            let limits = this.createElem("span",{module:"limits"},this.cssMap.pageBtn,null);

            let limitsSelect = this.createElem('select',{},{border:"unset"},null);

            for(let i in this.AttrConf.limits){

                let limit = this.AttrConf.limits[i];

                let attr = {

                    value: limit

                }

                if(this.AttrConf.limit == limit){

                    attr.selected = true;

                }

                limitsSelect.appendChild(this.createElem('option',attr,{},limit+"条/页"));

            }

            limits.appendChild(limitsSelect);

            this.modules.limits = limits;

        }

    }

    attr(dom,attrMap){

        Object.keys(attrMap).forEach(attr => dom.setAttribute(attr,attrMap[attr]));

    }

    css(dom,cssMap){

        Object.keys(cssMap).forEach(css => dom.style[css] = cssMap[css]);

    }

    createElemBase(elemTag,elemName){

        let elem  =  document.createElement(elemTag);

        if(elemName){

            elem.innerHTML = elemName;

        }

        return elem;

    }

    createElem(elemTag,attrMap,cssMap,elemName){

        let elem = this.createElemBase(elemTag,elemName);

        if(attrMap){

            this.attr(elem,attrMap);

        }

        if(cssMap){

            this.css(elem,cssMap);

        }

        return elem;

    }

}

/**

 * 分页工具对象 负责和调用方打交道, 同时协调AttrConf,ViewConf的属性和相关监听方法

 */

class PageUtil{

    AttrConf;

    ViewConf;

    config = {

        layout: {

            left:{

                show: true,

                modules: ['base'],

            },

            right:{

                modules:[,'prev','pages','next','limits','jump'],

            }

        },

        action: {

            toPage(index,limit){

                //实际使用的使用可以通过该方法获取到当前分页参数信息

            },

            error(info){

                console.log(info);

            }

        },

    };

    constructor(elem){

        this.elem = elem;

        if(typeof(elem) == "string"){

            this.elem = document.querySelector(elem);

        }

    }

    render(param){

        if(param){

            //首次使用的时候 需要先初始化 AttrConf对象

            this.AttrConf = param.AttrConf;

            this.ViewConf = new ViewConf(this.AttrConf);

            if(param.action){

                let action = param.action;

                if(action.toPage){

                    this.config.action.toPage = action.toPage;

                }

            }

            /* 初始化布局配置 */

            if(param.layout){

                let layout = param.layout;

                if(layout.left){

                    if(layout.left.show != undefined){

                        this.config.layout.left.show = layout.left.show;

                    }

                    if(layout.left.modules){

                        this.config.layout.left.modules = layout.left.modules;

                    }

                }

                if(layout.right){

                    if(layout.right.modules){

                        this.config.layout.left.modules = layout.left.modules;

                    }

                }

                //从新渲染下布局

                this.ViewConf.setLayout(this.config.layout);

            }

        }

        //从视图配置中把视图加载到页面, 完成按钮状态,事件的渲染

        this.loadPageViewToDom();

        this.renderPageBtnStyle();

        this.renderPageBtnAction();

    }

    loadPageViewToDom(){

        let inst = this;

        let layout = inst.config.layout;

        //初始化左容器视图

        if(layout.left.show){

            inst.elem.appendChild(this.ViewConf.layout.left.dom);

            inst.ViewConf.layout.left.ids.forEach(modeName => {

                inst.elem.querySelector("[layout=left]").appendChild(inst.ViewConf.modules[modeName]);

            })

        }

        inst.elem.appendChild(this.ViewConf.layout.right.dom);

        inst.ViewConf.layout.right.ids.forEach(modeName => {

            if(modeName == 'pages'){

                for(let i in inst.ViewConf.modules.pages){

                    let codeDom = inst.ViewConf.modules.pages[i];

                    inst.elem.querySelector("[layout=right]").appendChild(codeDom);

                }

            }else{

                inst.elem.querySelector("[layout=right]").appendChild(inst.ViewConf.modules[modeName]);

            }

        })

    }

    /**

     * 渲染分页按钮状态样式

     */

    renderPageBtnStyle(){

        let inst = this;

        //渲染按钮 经过 -- 按下 -- 离开样式

        let pressDowCss = inst.ViewConf.cssMap.pageBtnPressDown;

        let hoverCss = inst.ViewConf.cssMap.pageBtnHover;

        let baseCss = inst.ViewConf.cssMap.pageBtn;

        this.elem.querySelectorAll('[btn]:not([active]):not([disabled])').forEach(dom => {

            dom.addEventListener('mouseenter',

                () => inst.ViewConf.css(dom,hoverCss));

            dom.addEventListener('mousedown',

                () => inst.ViewConf.css(dom,pressDowCss));

            dom.addEventListener('mouseup',

                () => inst.ViewConf.css(dom,hoverCss));

            dom.addEventListener('mouseleave',

                () => inst.ViewConf.css(dom,baseCss));

        });

        //渲染禁用按钮样式

        let disabledCss = inst.ViewConf.cssMap.pageBtnDisabled;

        this.elem.querySelectorAll('[disabled]:not([active])').forEach(dom => {

            inst.ViewConf.css(dom,disabledCss);

        });

        //渲染当前选中按钮样式

        let activeCss = inst.ViewConf.cssMap.pageBtnCur;

        this.elem.querySelectorAll('[active]').forEach(dom => {

            inst.ViewConf.css(dom,activeCss);

        });

        if(inst.ViewConf.layout.left.show == true){

            let left = this.elem.querySelector('[layout=left]');

            inst.ViewConf.css(left,{

                display: 'table-cell'

            });

            left.setAttribute("algin","left");

        }

        let right = this.elem.querySelector('[layout=right]');

        inst.ViewConf.css(right,{

            display: 'table-cell',

            verticalAlign: 'middle',

        });

        right.setAttribute("align","right");

        this.ViewConf.css(this.elem,{

            display: "inline-table",

            width: "100%",

        });

        this.ViewConf.css(this.elem.querySelector("[module=base]"),this.ViewConf.cssMap.base);

    }

    /**

     * 渲染分页按钮事件

     */

    renderPageBtnAction(){

        let inst = this;

        //页码 上一页 下一页事件

        inst.elem.querySelectorAll("[btn]:not([active]):not([disabled])")

            .forEach(dom => dom.addEventListener('click',toPage));


        function toPage(e){

            let curPage = this.getAttribute("pagecode");


            inst.toPage(parseInt(curPage));

        }

        //跳转到指定页事件

        inst.elem.querySelector("[module=jump]>input").addEventListener('blur',(e)=>{

            let val = parseInt(e.target.value);

            if(isNaN(val)){

                inst.config.action.error({module:'jump',ele:e.target,type:'页码转换异常',msg:"页码错误,只能输入数字,实际输入值为:"+e.target.value});

                return;

            }

            val = val < 1 ? 1 : (val > inst.AttrConf.pageTotal ? inst.AttrConf.pageTotal : val);

            inst.toPage(val);

        });

        inst.elem.querySelector("[module=jump]>input").addEventListener('focus',(e)=>e.target.select());

        //每页显示配置事件

        inst.elem.querySelector("[module=limits]>select").addEventListener('change',(e)=>{

            let ele = e.target;

            let curIndex = ele.selectedIndex;

            let val = parseInt(ele.options[curIndex].value);

            inst.AttrConf.init({limit:val});

            inst.toPage(1);

            console.log(inst.AttrConf);

        });

    }

    /**

     * 跳转到指定页

     * @param {Number} pageCode

     */

    toPage(pageCode){

        //设置新页码

        this.AttrConf.setCurPage(pageCode);

        //暴露给需要分页对象的方法, 执行后 会重新初始化总数据条数

        this.config.action.toPage(pageCode,this.AttrConf.limit);

        this.AttrConf.initOthers();

        //重新初始化视图模型

        this.ViewConf.initModuls();

        //删除之前的旧页码

        this.elem.querySelector("[layout=right]").innerHTML = "";


        this.render();

    }

}

```

## 如何使用

* 在html中引入js代码

* 以下是可以直接运行的html演示代码, 可以直接coyp, 注意引用就行

  ```

  <!DOCTYPE html>

  <html lang="en">

  <head>

      <meta charset="UTF-8">

      <meta http-equiv="X-UA-Compatible" content="IE=edge">

      <meta name="viewport" content="width=device-width, initial-scale=1.0">

      <title>Document</title>

      <script src="./page-utils-v2.js"></script>

    <style>

        .box{

            padding: 30px;

            width:80% !important;

            border: 1px solid #ccc;

        }

    </style>

  </head>

  <body>

      <div id="page" class="box"></div>

      <div id="page1"class="box"></div>

      <div id="page2"class="box"></div>

      <div id="page3"class="box"></div>

      <script>

        // 创建分页对象, #page是需要放分页的容器选择器, 也可以是一个HTMLdom对象

          var pageUtil = new PageUtil("#page");

          var pageUtil1 = new PageUtil("#page1");

          var pageUtil2 = new PageUtil("#page2");

          var pageUtil3 = new PageUtil("#page3");


        // 第一次加载的时候,需要这样写

          pageUtil.render({

              AttrConf: new AttrConf(1,10,2020)

          });

        pageUtil1.render({

              AttrConf: new AttrConf(1,20,1668),

            layout: {

                left:{

                    show: true,

                    modules: ['base'],

                },

                right:{

                    modules:['prev','pages','next','limits','jump'],

                }

            }

          });

        pageUtil2.render({

              AttrConf: new AttrConf(1,10,128),

            action: {

                toPage(index,limit){

                    //实际使用的使用可以通过该方法获取到当前分页参数信息

                },

                error(info){

                    console.log(info);

                }

            },

          });

        pageUtil3.render({

              AttrConf: new AttrConf(1,10,123),

            layout: {

                left:{

                    show: true,

                    modules: ['base'],

                },

                right:{

                    modules:['prev','next','limits','jump'],

                }

            }        

          });


        // 后续高级用法 等有时间整理好了文档在补充

      </script>

  </body>

  </html>

  ```

## 效果预览

如有不足之情, 恳请大佬们能在评论区留下意见 谢谢大家

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,302评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,563评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,433评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,628评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,467评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,354评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,777评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,419评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,725评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,768评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,543评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,387评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,794评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,032评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,305评论 1 252
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,741评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,946评论 2 336

推荐阅读更多精彩内容