---
title: "模仿百度后台分页组件"
author: "f543711700"
date: "2013-12-23T10:12:46Z"
tags: []
categories: ["非技术"]
slug: "untitled"
draft: false
lastmod: "2013-12-23T10:12:46Z"
id: 1993838
url: "https://f543711700.iteye.com/blog/1993838"
---

效果如下： \[img]http://dl2.iteye.com/upload/attachment/0092/4120/3f4b4cf6-fd85-37f7-9145-f2fd5b585e50.png\[/img] 代码如下： \[code="java"]public String createPageHtml(int totalPages,int pageNo,int showPages,String href) { String htmlstr = ""; if(totalPages &lt;= 1) {//只有1页，直接返回空串 return htmlstr; } else { if(pageNo &lt;= 0 || pageNo &gt; totalPages) { pageNo = 1; } String href1 = href + "?totalPages=" + totalPages + "&showPages=" + showPages + "&pageNo="; if(pageNo != 1) { String href2 = href1 + (pageNo-1); htmlstr = "

[&lt;上一页](%5C%22%22)

"; } int loopCount = showPages; int mod = totalPages % showPages; //计算总组数 int a = (mod == 0) ? totalPages / showPages : (totalPages / showPages) + 1; //这个a1是代表当前pageNo位于第几组 int a1 = pageNo%showPages == 0 ? (pageNo/showPages) : (pageNo/showPages) + 1; if(a == a1 && mod &gt; 0) { loopCount = mod; } //这个startPage是代表当前pageNo所属组的一个元素编号的变量 //计算公式是: showPages * 第几组 - showPages + 1 int startPage = (showPages * a1) - showPages + 1; for(int i = 1; i &lt;= loopCount; i++) { String href3 = href1 + startPage; String s = "

[" + startPage + "](%5C%22%22)

"; if(startPage == pageNo) { s = "

[" + startPage + "](%5C%22%22)

"; } htmlstr = htmlstr + s; startPage ++; } String href4 = href1 + (pageNo+1); htmlstr = htmlstr + "

[&gt;下一页](%5C%22%22)

"; } return htmlstr; }\[/code] css如下： \[code="java"].currPage { float:left; width: 18px; height: 18px; text-align: center; line-height:18px; margin-right: 5px; font-size: 13px; text-decoration: none; } .fontPage { float:left; border: 1px solid; width: 60px; height: 18px; border-color: gray; text-align: center; line-height:18px; margin-right: 5px; font-size: 12px; } .normalPage { float:left; border: 1px solid; width: 18px; height: 18px; border-color: gray; text-align: center; line-height:18px; margin-right: 5px; font-size: 13px; text-decoration: none; }\[/code] 调用方式如下： \[code="java"]&lt;%=new PageServlet().createPageHtml(totalPages,pageNo,showPages,href) %&gt;\[/code]