一、简介
剧情需要,找遍网络没找到合适的,由此想自己封装一个,主要是思路问题,理清思路很重要,这里我的思路采用了一个稍微简单的。
二、代码
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>分页插件</title> </head> <style type="text/css"> .box{ display: flex; align-items: center; justify-content: space-around; width: 60%; margin: 0 auto; } .box span{ display: flex; padding: 5px 10px; align-items: center; justify-content: center; border: 1px solid #000; cursor: pointer; } .pageBox{ display: flex; flex-direction: row; justify-content: space-around; } .pageBox .active{ background: #000; color: #fff; } </style> <body> <div class="box" id="pagebox"> <span class="prev">上一页</span> <div class="pageBox"> <span class="active">1</span> <span>2</span> <span>3</span> <span>4</span> <span>5</span> </div> <span class="next">下一页</span> </div> </body> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script> <script> (function($){ $.Init = function(params){ var defaults = { //根元素 el:‘#page‘, // 当前页 current:5, // 按钮显示个数====设置为单数 btnSize:5, // 每页列表个数 listSize:10, //数据总记录数 dataSize:300, // 回调函数 callBack:‘callBack‘ }; var params = params ? params : {}; var config = $.extend(defaults,params); var pageSize = (config.dataSize%config.listSize ==0) ? (config.dataSize/config.listSize) : parseInt(config.dataSize/config.listSize)+1; var nodeList; Page(config.current) //dom渲染 function Render(start,end,current){ var prev = ‘‘, next = ‘‘, str = ‘‘, pageStr = ‘‘; prev = "<span class=‘prev‘>上一页</span>"; next = "<span class=‘next‘>下一页</span>"; for(var i = start; i<=end; i++){ if(i==current){ pageStr+="<span class=‘active‘ attr-index=‘"+i+"‘>"+i+"</span>" }else{ pageStr+="<span attr-index=‘"+i+"‘>"+i+"</span>" } } pageStr= "<div class=‘pageBox‘>"+pageStr+"</div>"; str+= prev+pageStr+next; $(config.el).empty().append(str) clickFun() } //判断逻辑 function Page(current){ if(current<=0 || current > pageSize){ var current = 1 }else{ var current = current if(current <= 2 && current>0){ Render(1,5,current) }else if(current>pageSize-2 && current<=pageSize){ Render(pageSize-4,pageSize,current) }else{ Render(current-2,current+2,current) } } } //绑定click事件 function clickFun(){ nodeList = $(".pageBox span"); $.each(nodeList,function(i,v){ $(v).on(‘click‘,function(){ var current = parseInt($(this).attr(‘attr-index‘)) Page(current) }) }) //prev $(‘.prev‘).click(function(){ var current = parseInt($(‘.active‘).attr(‘attr-index‘))-1; if(current < 1){ $(this).css(‘cursor‘,‘not-allowed‘) return false }else{ Page(current) } }) //next $(‘.next‘).click(function(){ var current = parseInt($(‘.active‘).attr(‘attr-index‘))+1; if(current > pageSize){ $(this).css(‘cursor‘,‘not-allowed‘) return false }else{ Page(current) } }) } } })(jQuery); $.Init({ el:"#pagebox", current:3, }) </script> </html>
原文地址:https://www.cnblogs.com/helloNico/p/11107431.html
时间: 2024-09-30 19:56:06