三、分页控件yqPaginator.js的使用

分页,在实习期间参与的项目中基本都会用到,除此之外还有移动端点击加载更多之类的(以后总结)。

分页使用场景案例:
分页使用场景

这个功能的实现,我借助了一个插件yqPaginator.js。

相关文件我会放到文章末尾。

如何使用此插件

  • 引入yqPaginator.js 与 yqPaginator.css 文件
  • 在需要添加分页器的地方加入该元素 <div id="pagination" onselectstart="return false" style="text-align: right;"></div> (onselectstart="return false"是为了防止鼠标点击时选中文字,style="text-align: right;" 是使分页器右对齐布局)
  • 初始化分页器:
var paginationOne = new YqPaginator ( '#pagination' , {
                                   total : Math.ceil ( totalCount / size ) ,      //总页数
                                   current : 1 ,       //默认选中页码
                                   onChange : function ( page ) {
                                       //点击页码,page发生改变时,执行操作       
                                   },
                                   isInputVisible:false  //是否显示页码输入框
                             });
  • 根据需求可以更改页码的样式,插件默认是正方形,在浏览器中F12调试中,可以查看不同元素的样式设置,找到对应的选择器,在yqPaginator.css修改其样式
  • 如何实现点击页码加载不同数据:(这里要注意一个问题,即分页器的初始化和非初始化,只有第一次加载数据时,才会初始化创建一个分页器,当再点击第二页,再次发起请求获取数据时,就不需要再创建一个新的分页器了。我用了一个isInit参数进行控制,具体查看实例代码)
 function getInfo ( page , size , isInit ) {    //参数:页码、一页加载几条数据、是否初始化分页器
         $.ajax({
            type :  'GET',
            url : '/api/article/getbypid?id=8&page='+page+'&pagesize='+size ,  //后台提供的接口,需要我提供当前模块的id(如“全部活动”模块的id为8),页码,每一页的条数
            dataType : 'json',
            success : function ( result ) {
               var data = result.data,
                   articleArr = data.articles, //文章组成的数组
                   slot = '',        //插槽字符串
                   title = '',        //文章标题
                   time = '',       //文章时间
                   articleId = 0,    //文章ID
                   totalCount = data.Total;     // 文章总数
               if( articleArr.length > 0){
                    for (var i = 0 ; i < articleArr.length; i++ ) {
                        title = articleArr[i].title;
                        if ( articleArr[i].createTime != null ) {
                            time = formatDate( articleArr[i].createTime );   //这是一个时间戳转2018-11-6格式时间的方法,以后再写
                        }
                        articleId = articleArr[i].articleid;
                        slot += '<a href="article-read.jsp?articleId='+articleId+ '" target="_blank" title="'+title+'"><span>■</span>'+title+'<span class="fr">'+time+'</span></a>';   //将要渲染的页面元素用字符串拼接起来
                    }
                    $( '.allActivities' ).html( slot );  //将上面拼接的字符串直接插入到其容器中(css提前设置好样式哦)
                    
                  //如果是初始化,则添加分页空控件
                    if ( isInit ) {   //只有isInit判定为真,才能执行下面代码
                        if ( Math.ceil ( totalCount / size ) <= 1) {   //总条数 / 每页条数 = 总页数,如果总页数都小于等于1,则不需要分页~
                            $('#pagination').remove();   //将之移除就好啦
                        } else {
                            var paginationOne = new YqPaginator( '#paginationTwo' , { 
                                   total : Math.ceil ( totalCount / size ) ,
                                   current : 1 ,
                                   onChange : function ( page ) {
                                       getInfo ( page , 10,0 )     //调用自身,参数:page为当前点击的页码,10为每页10条数据, 0 即为非初始化!       
                                   },
                                   isInputVisible:false
                               });
                         }
                        }    
                 }
            }
        })
 }

getInfo(1,10,1)   //调用,参数:1为初始页码,10为每页10条数据, 1 为初始化分页!  
     

分页功能的实现,还是要看后端提供的接口需要哪些参数来决定哦~

由于此插件是同时发给我的,我在网上没有搜到,那。。。。就把源代码摆在这里吧,以防此后文件丢失hia~ hia~ hia~~~

yqPaginator.js

'use strict';
(function() {
    var YqPaginator = function YqPaginator(container, params) {
        var defaults = {
            current: 1,
            total: 0,
            onChange: null,
            container: $(container),
            isInputVisible: true
        };
        this.params = $.extend({}, defaults, params);
        if (this.params.container.length > 1) {
            this.params.container = this.params.container.eq(0);
        }
        this.init();
    };
    YqPaginator.prototype = {
        init: function init() {
            this.render();
            this.bind();
        },
        render: function render() {
            var total = this.params.total,
                current = this.params.current;
            if (!this.isNumber(total) || !this.isNumber(current)) {
                throw new Error('[YqPaginator] total/current should be a number');
            }
            if (total <= 0 || current <= 0) {
                throw new Error('[YqPaginator] total and current should greater than zero');
            }
            if (current > total) {
                throw new Error('[YqPaginator] current could not greater than total');
            }
            var insert = '',
                oWrap = $('<div class="yqPaginator-wrap"></div>'),
                oUl = $('<ul class="yqPaginator-ul"></ul>'),
                i = 0;
            if (total < 8) {
                if (total == 1) {
                    insert += '<li data-page="1">1</li>';
                } else {
                    insert += '<li class="yqPaginator-prev">&lt;</li>';
                    for (i = 1; i <= total; i++) {
                        insert += '<li data-page="' + i + '" class="yqPaginator-page">' + i + '</li>';
                    }
                    insert += '<li class="yqPaginator-next">&gt;</li>';
                }
            } else {
                insert += '<li class="yqPaginator-prev">&lt;</li><li class="yqPaginator-first yqPaginator-page" data-page="1">1</li><li class="yqPaginator-dots" is-visible="1">...</li>';
                var iVal = 0;
                if (current > 4 && current < total - 3) {
                    iVal = current - 2;
                } else {
                    if (current <= 4) {
                        iVal = 2;
                    } else if (current >= total - 3) {
                        iVal = total - 5;
                    }
                }
                for (i = iVal; i < iVal + 5; i++) {
                    insert += '<li class="yqPaginator-page" data-page="' + i + '">' + i + '</li>';
                }
                insert += '<li class="yqPaginator-dots" is-visible="1">...</li><li class="yqPaginator-last yqPaginator-page" data-page="' + total + '">' + total + '</li><li class="yqPaginator-next">&gt;</li>';
            }
            oUl.append(insert);
            if (total >= 8) {
                if (current <= 4) {
                    oUl.find('.yqPaginator-dots').eq(0).hide().attr('is-visible', '0');
                } else if (current >= total - 3) {
                    oUl.find('.yqPaginator-dots').eq(1).hide().attr('is-visible', '0');;
                }
            }
            oUl.find('.yqPaginator-page[data-page="' + current + '"]').addClass('yqPaginator-current');
            oUl.appendTo(oWrap);
            if (total >= 8 && this.params.isInputVisible) {
                var oInputWrap = $('<div class="yqPaginator-inputWrap"><span>共 ' + total + '页,到第</span><input type="text" class="yqPaginator-input"/><span>页</span><button class="yqPaginator-btn">确定</button></div>');
                oInputWrap.appendTo(oWrap);
            }
            oWrap.appendTo(this.params.container);
        },
        isNumber: function isNumber(val) {
            return !isNaN(parseInt(val));
        },
        bind: function bind() {
            var container = this.params.container,
                _this = this;
            container.find('.yqPaginator-prev').on("click", function() {
                if (_this.params.current == 1) return;
                _this.params.current--;
                _this.switchPage();
            });
            container.find('.yqPaginator-next').on("click", function() {
                if (_this.params.current == _this.params.total) return;
                _this.params.current++;
                _this.switchPage();
            });
            container.find('.yqPaginator-page').on("click", function() {
                _this.params.current = parseInt($(this).text());
                _this.switchPage();
            });
            if (this.params.total >= 8 && this.params.isInputVisible) {
                container.find('.yqPaginator-btn').on("click", function() {
                    var oVal = parseInt($(this).siblings('.yqPaginator-input').val());
                    if (_this.isNumber(oVal) && oVal <= _this.params.total) {
                        _this.params.current = oVal;
                        _this.switchPage();
                    }
                });
                container.find('.yqPaginator-input').on("keydown", function(event) {
                    var ev = event || window.event;
                    if (ev.keyCode == 13) {
                        var oVal = parseInt($(this).val());
                        if (_this.isNumber(oVal) && oVal <= _this.params.total) {
                            _this.params.current = oVal;
                            _this.switchPage();
                        }
                    }
                });
            }
        },
        switchPage: function switchPage() {
            var current = this.params.current,
                total = this.params.total,
                container = this.params.container,
                oUl = container.find('.yqPaginator-ul'),
                oPageList = oUl.find('.yqPaginator-page');
            if (total >= 8) {
                var oDotList = oUl.find('.yqPaginator-dots'),
                    i = 0,
                    j = 0;
                if (current > 4 && current < total - 3) {
                    for (i = 0; i < oDotList.length; i++) {
                        if (parseInt(oDotList.eq(i).attr('is-visible')) == 0) {
                            oDotList.eq(i).css('display', 'inline-block').attr('is-visible', '1');
                        }
                    }
                    j = current - 2;
                } else {
                    if (current <= 4) {
                        if (parseInt(oDotList.eq(0).attr('is-visible')) == 1) {
                            oDotList.eq(0).hide().attr('is-visible', '0');
                        }
                        if (parseInt(oDotList.eq(1).attr('is-visible')) == 0) {
                            oDotList.eq(1).css('display', 'inline-block').attr('is-visible', '1');
                        }
                        j = 2;
                    } else if (current >= total - 3) {
                        if (parseInt(oDotList.eq(1).attr('is-visible')) == 1) {
                            oDotList.eq(1).hide().attr('is-visible', '0');
                        }
                        if (parseInt(oDotList.eq(0).attr('is-visible')) == 0) {
                            oDotList.eq(0).css('display', 'inline-block').attr('is-visible', '1');
                        }
                        j = total - 5;
                    }
                }
                for (i = 1; i < 6; i++, j++) {
                    oPageList.eq(i).text(j).attr('data-page', j);
                }
            }
            oPageList.removeClass('yqPaginator-current');
            oPageList.filter('[data-page="' + current + '"]').addClass('yqPaginator-current');
            if (this.params.onChange) {
                this.params.onChange(current);
            }
        }
    };
    window.YqPaginator = YqPaginator;
})();

YqPaginator.css

.yqPaginator-wrap *{
    box-sizing: border-box;
}
.yqPaginator-ul{
    display: inline-block;
    vertical-align: middle;
    height: 40px;
    overflow-y: hidden;
}
.yqPaginator-ul li{
    display: inline-block;
    box-sizing: border-box;
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    color: #666;
    border:1px solid #e6e6e6;
    cursor: pointer;
    margin-left: -1px;
    font-size: 14px;
}
.yqPaginator-ul .yqPaginator-dots{
    color: #999;
    border: none;
}
.yqPaginator-ul .yqPaginator-current{
    background: #1E3B4B;
    color: #fff;
    border:1px solid #1E3B4B;
}

.yqPaginator-inputWrap{
    display: inline-block;
    vertical-align: middle;
    color: #999;
    font-size: 12px;
    line-height: 20px;
    margin-left: 10px;
}
.yqPaginator-input{
    width: 30px;
    margin: 0 3px;
    line-height: 20px;
    height: 18px;
    padding: 0;
    border:1px solid #e6e6e6;
    outline: none;
}
.yqPaginator-btn{
    background: none;
    border:1px solid #e6e6e6;
    color: #666;
    margin-left: 10px;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,815评论 1 92
  • ~~其实英文的代码对于中文输入,尤其是手机中文输入来说很不友好~~ *但是也没关系啦* **反正闲着也是闲着** ...
    抹茶流苏阅读 298评论 0 0
  • 大家看到这个题目的时候有没有种青葱的味道呢?是的,我想讲的故事就是关于我青葱岁月。我特意问了一下度娘,什么是青葱岁...
    昕橦阅读 168评论 0 0
  • 文/于格 1964年,美国纽约发生了一起案件——3月13日,凌晨三点钟,一名年轻女孩基蒂在回家的路上,遭遇了一名歹...
    于格YUGE阅读 7,003评论 9 9
  • 10:30睡觉 6:30起床 吃饭 运动 上午10吃干果
    越流阅读 91评论 0 0