模仿百度后台分页组件

效果如下:



代码如下:
public String createPageHtml(int totalPages,int pageNo,int showPages,String href) {
		String htmlstr = "";
		if(totalPages <= 1) {//只有1页,直接返回空串
			return htmlstr;
		} else {
			if(pageNo <= 0 || pageNo > totalPages) {
				pageNo = 1;
			}
			
			String href1 = href + "?totalPages=" + totalPages + "&showPages=" + showPages + "&pageNo=";
			
			if(pageNo != 1) {
				String href2 = href1 + (pageNo-1); 
				htmlstr = " <div class=\"fontPage\"><a href=\"" +href2 + "\" style=\"text-decoration: none;\">&lt;上一页</a></div> ";
			}
			
			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 > 0) {
				loopCount = mod;
			}
			
			//这个startPage是代表当前pageNo所属组的一个元素编号的变量
			//计算公式是: showPages * 第几组 - showPages + 1
			int startPage = (showPages * a1) - showPages + 1;  
			
			for(int i = 1; i <= loopCount; i++) {
				String href3 = href1 + startPage; 
				String s = " <div class=\"normalPage\"><a href=\"" + href3 + "\" style=\"text-decoration: none;\">" + startPage + "</a></div> ";
				if(startPage == pageNo) {
					s = " <div class=\"currPage\"><a href=\"" + href3 +  "\" style=\"text-decoration: none;\">" + startPage + "</a></div> ";
				}
				htmlstr = htmlstr + s;
				startPage ++;
			}
			String href4 = href1 + (pageNo+1); 
			htmlstr = htmlstr + " <div class=\"fontPage\"><a href=\"" + href4 + "\" style=\"text-decoration: none;\">&gt;下一页</a></div> ";
		}
		return htmlstr;
		
	}


css如下:
.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;
}


调用方式如下:
<%=new PageServlet().createPageHtml(totalPages,pageNo,showPages,href) %>


猜你喜欢

转载自f543711700.iteye.com/blog/1993838