一页孤舟

学海无涯

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

下图是目前比较流行的客户端导航菜单,几乎随处可见:

 


这个菜单的核心思想是让用户选择的页(即当前页)尽量居于菜单的中心。如

 

 

 

 

 自己想了个算法,和大家分享下。

主要思路:菜单应在客户端用js脚步动态生成,生成菜单应从服务器端接受三个参数:

pageCount:分页的总页数

currentPage:当前页

showpage:导航显示的页数,为一常数值(上图例中为4)

分两种情况考虑:

1、分页总页数 小于导航显示的页数

此处无需做任何处理

2、分页总页数 大于导航显示的页数

 此处再分3种情况考虑:

  • 处理当前页为前几页的情况
  • 处理当前页为后几页的情况
  • 当前页在总页数的中间 
为了简单便于理解,用c#代码模拟实现了下,实际应用中换成js即可:
代码
namespace ConsoleApplication4
{
    
class Program
    {
        
static void Main(string[] args)
        {
            
const int showPage = 7;//页面显示数
            const int pageCount = 15;//总页数
            const int currentPage = 8;//当前页
            Print(showPage, pageCount, currentPage);
            
        }

        
static void Print(int showPage, int pageCount, int currentPage)
        {
            
if (pageCount < showPage)//总页数小于页面显示数
            {
                
for (int i = 0; i < currentPage; i++)
                {
                    Console.Write(
"page{0} ", i);

                }
                Console.Write(
"current Page{0} ", currentPage);
                
for (int i = currentPage + 1; i < pageCount; i++)
                {
                    Console.Write(
"page{0} ", i);
                }
            }
            
else//总页数大于页面显示数
            {
                
if (currentPage < showPage / 2)//当前页小于显示页数的一半:处理当前也为前几页的情况
                {
                    
for (int i = 0; i < currentPage; i++)
                    {
                        Console.Write(
"page{0} ", i);

                    }
                    Console.Write(
"current Page{0} ", currentPage);
                    
for (int i = currentPage + 1; i < showPage; i++)
                    {
                        Console.Write(
"page{0} ", i);
                    }
                }
                
else if (pageCount - currentPage < showPage / 2)//总页数与当前页的差值小于显示页数的一半:处理当前页为后几页的情况
                {
                    
for (int i = pageCount - showPage; i < currentPage; i++)
                    {
                        Console.Write(
"page{0} ", i);
                    }
                    Console.Write(
"current Page{0} ", currentPage);
                    
for (int i = currentPage + 1; i < pageCount; i++)
                    {
                        Console.Write(
"page{0} ", i);
                    }
                }
                
else//正常处理:当前页在总页数的中间
                {
                    
for (int i =currentPage-showPage/2; i < currentPage; i++)
                    {
                        Console.Write(
"page{0} ", i);
                    }
                    Console.Write(
"current Page{0} ", currentPage);
                    
for (int i = currentPage+1; i < currentPage+1+showPage/2; i++)
                    {
                        Console.Write(
"page{0} ", i);
                    }
                }
            }
        }
    }
}


 

posted on 2009-12-07 17:34  LinLi  阅读(364)  评论(0编辑  收藏  举报