0
点赞
收藏
分享

微信扫一扫

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

color_小浣熊 2022-04-03 阅读 26
javascript

工具源码

/**
 * 分页参数配置对象,用于配置分页参数信息
 */
 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>
    

效果预览

在这里插入图片描述

举报

相关推荐

0 条评论