<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <div id="pages"></div> <span id="page"></span> <script> var TOTALBUTTOM = 10; //为了对称美观,请设置翻页按钮为奇数 var total = 10; //用ajax动态赋值即可(此处写死一个数据模拟ajax返回的值) pagecontroller = function(page) { var beginpage, endpage; var pageno = parseInt(page) if (total > TOTALBUTTOM) { //当保证足够TOTALBUTTOM个按钮 if (pageno - parseInt(TOTALBUTTOM / 2) < 1) { //如果page离1不足TOTALBUTTOM/2个位置 beginpage = 1; endpage = beginpage + TOTALBUTTOM - 1; } else { beginpage = pageno - parseInt(TOTALBUTTOM / 2); endpage = pageno + parseInt(TOTALBUTTOM / 2); } //先保证不下溢 if (endpage >= total) { endpage = total; } //再保证不上溢 if (endpage - pageno < parseInt(TOTALBUTTOM / 2)) { // 向下补充按钮 endpage = total; beginpage = total - TOTALBUTTOM + 1; } // 向下补充按钮 else if (pageno - beginpage < parseInt(TOTALBUTTOM / 2)) { // 向上补充按钮 beginpage = 1; endpage = beginpage + TOTALBUTTOM - 1; } // 向上补充按钮 else { //一般情况(即当前页码位于最中间的情况) beginpage = pageno - parseInt(TOTALBUTTOM / 2); endpage = pageno + parseInt(TOTALBUTTOM / 2); } } //当保证足够TOTALBUTTOM个按钮 else if (total <= TOTALBUTTOM) { //按钮数不足总页数 beginpage = 1; endpage = total; } //直接固定开头结尾就好 var html = ""; for (var i = beginpage; i <= endpage; i++) { html += "<button id='pages' value='" + i + "' onclick =pagecontroller(value)>" + i +"</button>"; //使用字符串拼接的方式将页码按钮动态更新 } document.getElementById("pages").innerHTML = html; document.getElementById("page").innerHTML = "当前第" + pageno + "页" + "<br>共" + total + "页"; } window.onload = function() { pagecontroller(1); //初始进来的时候的页面 } </script> </body> </html>