博客园生成目录 博客园生成目录

时间:2021年1月31日

博客园的文章生成目录

可搜索到的目录生成代码主要是只能识别出两级,h1与h2或者是h2和h3

未能满足我的需求

我对这些代码进行了修改优化

同时会贴出我在网上找到的其他目录生成代码:h1与h2或者是h2和h3

修改后的代码可识别h1~h6共6级目录,附上css美化代码

但要求要从h1级开始逐级变化才可以识别,若不是从h1级目录开始或者目录层级没有逐级变化,则无法正确识别

一 可识别h1-h6级目录

附有js代码和css样式表,js插入的html中带有基本的style样式,css只是在此基础上再次美化,可有可无。

js代码

我是直接将js的文件上传到博客园文件,再在页脚代码处引入。

要在页脚代码引入(页面加载后运行),如果不是,则要将代码放入window.onload = function(){};中。

// 生成目录索引列表
// ref: http://www.cnblogs.com/wangqiguo/p/4355032.html
// modified by: zzq 
function GenerateContentList()
{
    let mainContent = $('#cnblogs_post_body');
    //获取h1
    let h1_list = $('#cnblogs_post_body h1');//如果你的章节标题不是h1,只需要将这里的h1换掉即可

    if(mainContent.length < 1)
        return;
 
    if(h1_list.length>0)
    {
        let content = '<a name="_labelTop"></a>';
        content += '<div >';
        content += '<p style="font-size:18px;"><b>目录</b></p>';
        content += '<ul class="myCatalog1">';
        //h1中的项循环逐渐显示/////////////////////////////////////////////////////////////////////////////////////
        for(let i=0; i<h1_list.length; i++)
        {
            // 在h1之前插入定位点
            let go_to_top = '<div style="text-align: right;"><a href="#_labelTop" style="color:#f68a33">回到顶部</a><a name="_label' + i + '"></a></div>';
            $(h1_list[i]).before(go_to_top);
            
            //获取h1的项目下的h2列表
            let h2_list = $(h1_list[i]).nextAll("h2");
            let li2_content = ''; //h2的内容
            //h2循环列表/////////////////////////////////////////////////////////////////////////////////////////
            for(let j=0; j<h2_list.length; j++)
            {
                //获取h2下h3列表
                let h3_list = $(h2_list[j]).nextAll("h3");
                let li3_content = '';
                //h3循环列表/////////////////////////////////////////////////////////////////////////////////////
                for(let i3 = 0; i3<h3_list.length; i3++)
                {
                    //获取h3下h4列表
                    let h4_list = $(h3_list[i3]).nextAll("h4");
                    let li4_content = '';
                    //h4循环列表/////////////////////////////////////////////////////////////////////////////////////
                    for(let i4 = 0; i4<h4_list.length; i4++)
                    {
                        //获取h4下h5列表
                        let h5_list = $(h4_list[i4]).nextAll("h5");
                        let li5_content = '';
                        //h5循环列表/////////////////////////////////////////////////////////////////////////////////////
                        for(let i5 = 0; i5<h5_list.length; i5++)
                        {

                            //获取h5下h6列表
                            let h6_list = $(h5_list[i5]).nextAll("h6");
                            let li6_content = '';
                            //h6循环列表/////////////////////////////////////////////////////////////////////////////////////
                            for(let i6 = 0; i6<h6_list.length; i6++)
                            {

                                //h6项目中的内容
                                let tmp = $(h6_list[i6]).prevAll('h5').first();
                                if(!tmp.is(h5_list[i5]))
                                    break;
                                let li6_anchor = '<a name="_label' + i + '_' + j + '_' + i3 + '_' + i4 + '_' + i5 + '_' + i6 + '"></a>';
                                $(h6_list[i6]).before(li6_anchor);

                                li6_content += '<li class="myItem6"><a href="#_label' + i + '_' + j + '_' + i3 + '_' + i4 + '_' + i5 + '_' + i6 + '">' + $(h6_list[i6]).text() + '</a></li>';

                            }
                            //h5项目中的内容
                            let tmp = $(h5_list[i5]).prevAll('h4').first();
                            if(!tmp.is(h4_list[i4]))
                                break;
                            let li5_anchor = '<a name="_label' + i + '_' + j + '_' + i3 + '_' + i4 + '_' + i5 + '"></a>';
                            $(h5_list[j]).before(li5_anchor);

                            //将h6拼接到h5上
                            if(li6_content.length > 0)
                                li5_content += '<li class="myItem5"><a href="#_label' + i+ '_' + j + '_' + i3 + '_' + i4 + '_' + i5 + '">' + $(h5_list[i5]).text() + '</a><ul class="myCatalog5">' + li6_content + '</ul></li>';
                            else
                                li5_content += '<li class="myItem5"><a href="#_label' + i + '_' + j + '_' + i3 + '_' + i4 + '_' + i5 + '">' + $(h5_list[i5]).text() + '</a></li>';
                            
                        }
                        //h4项目中的内容
                        let tmp = $(h4_list[i4]).prevAll('h3').first();
                        if(!tmp.is(h3_list[i3]))
                            break;
                        let li4_anchor = '<a name="_label' + i + '_' + j + '_' + i3 + '_' + i4 + '"></a>';
                        $(h4_list[i4]).before(li4_anchor);

                        //将h5拼接到h4上
                        if(li5_content.length > 0)
                            li4_content += '<li class="myItem4"><a href="#_label' + i+ '_' + j + '_' + i3 + '_' + i4 + '">' + $(h4_list[i4]).text() + '</a><ul class="myCatalog4">' + li5_content + '</ul></li>';
                        else
                            li4_content += '<li class="myItem4"><a href="#_label' + i + '_' + j + '_' + i3 + '_' + i4 + '">' + $(h4_list[i4]).text() + '</a></li>';
                    }
                    //h3项目中的内容
                    let tmp = $(h3_list[i3]).prevAll('h2').first();
                    if(!tmp.is(h2_list[j]))
                        break;
                    let li3_anchor = '<a name="_label' + i + '_' + j + '_' + i3 + '"></a>';
                    $(h3_list[i3]).before(li3_anchor);

                    //将h4拼接到h3上
                    if(li4_content.length > 0)
                        li3_content += '<li class="myItem3"><a href="#_label' + i+ '_' + j + '_' + i3 + '">' + $(h3_list[i3]).text() + '</a><ul class="myCatalog3">' + li4_content + '</ul></li>';
                    else
                        li3_content += '<li class="myItem3"><a href="#_label' + i + '_' + j + '_' + i3 + '">' + $(h3_list[i3]).text() + '</a></li>';

                }
                //h2项目中的内容
                let tmp = $(h2_list[j]).prevAll('h1').first();
                if(!tmp.is(h1_list[i]))
                    break;
                let li2_anchor = '<a name="_label' + i + '_' + j + '"></a>';
                $(h2_list[j]).before(li2_anchor);

                //将h3拼接到h2上
                if(li3_content.length > 0)
                    li2_content += '<li class="myItem2"><a href="#_label' + i+ '_' + j + '">' + $(h2_list[j]).text() + '</a><ul class="myCatalog2">' + li3_content + '</ul></li>';
                else
                    li2_content += '<li class="myItem2"><a href="#_label' + i + '_' + j + '">' + $(h2_list[j]).text() + '</a></li>';
            }
            
            let li1_content = '';
            //将h2拼接到h1上
            if(li2_content.length > 0)
                li1_content = '<li class="myItem1"><a href="#_label' + i + '">' + $(h1_list[i]).text() + '</a><ul class="myCatalog2">' + li2_content + '</ul></li>';
            else
                li1_content = '<li class="myItem1"><a href="#_label' + i + '">' + $(h1_list[i]).text() + '</a></li>';
            content += li1_content;
        }

        content += '</ul>';
        content += '</div><p> </p>';
        // content += '<hr style="height:1px;border:none;border-top:1px dashed #0066CC;"/>';
        if($('#cnblogs_post_body').length != 0 )
        {
            $($('#cnblogs_post_body')[0]).prepend(content);//将全部内容加入dom
        }
    }   
}

GenerateContentList();

css代码

以下css代码是在我已有css代码的基础上写的,可能有部分地方不适用。上文的js中已经包括有样式了,可以不使用。

ul[class^="myCatalog"] {
    list-style-type: none !important;
    border-left: 1px #55895B dashed;
    margin: 10px 0;
}

li[class^="myItem"] {
    list-style-type: none !important;
    margin: 5px 0 5px 2px;
}

li[class^="myItem"] a {
    color: black;
}

li[class^="myItem"] a:hover {
    text-decoration: underline;
}

ul.myCatalog1{
    margin-left: 0 !important;
    border: 1px #55895B dashed;
    border-radius: 4px;
}

效果展示

博客园生成目录
博客园生成目录

博客园生成目录
博客园生成目录

二 h1与h2

效果和显示h1-h6目录的效果相同,只是层级减少为2个。

<script language="javascript" type="text/javascript">
// 生成目录索引列表
// ref: http://www.cnblogs.com/wangqiguo/p/4355032.html
// modified by: zzq
function GenerateContentList()
{
    var mainContent = $('#cnblogs_post_body');
    var h1_list = $('#cnblogs_post_body h1');//如果你的章节标题不是h2,只需要将这里的h2换掉即可

    if(mainContent.length < 1)
        return;
 
    if(h1_list.length>0)
    {
        var content = '<a name="_labelTop"></a>';
        content += '<div >';
        content += '<p style="font-size:18px;"><b>目录</b></p>';
        content += '<ul>';
        for(var i=0; i<h1_list.length; i++)
        {
            var go_to_top = '<div style="text-align: right;"><a href="#_labelTop" style="color:#f68a33">回到顶部</a><a name="_label' + i + '"></a></div>';
            $(h1_list[i]).before(go_to_top);
            
            var h2_list = $(h1_list[i]).nextAll("h2");
            var li2_content = '';
            for(var j=0; j<h2_list.length; j++)
            {
                var tmp = $(h2_list[j]).prevAll('h1').first();
                if(!tmp.is(h1_list[i]))
                    break;
                var li2_anchor = '<a name="_label' + i + '_' + j + '"></a>';
                $(h2_list[j]).before(li2_anchor);
                li2_content += '<li><a href="#_label' + i + '_' + j + '">' + $(h2_list[j]).text() + '</a></li>';
            }
            
            var li1_content = '';
            if(li2_content.length > 0)
                li1_content = '<li><a href="#_label' + i + '">' + $(h1_list[i]).text() + '</a><ul>' + li2_content + '</ul></li>';
            else
                li1_content = '<li><a href="#_label' + i + '">' + $(h1_list[i]).text() + '</a></li>';
            content += li1_content;
        }
        content += '</ul>';
        content += '</div><p> </p>';
        content += '<hr style="height:1px;border:none;border-top:1px dashed #0066CC;"/>';
        if($('#cnblogs_post_body').length != 0 )
        {
            $($('#cnblogs_post_body')[0]).prepend(content);
        }
    }   
}

GenerateContentList();
</script>

三 h2和h3

<script language="javascript" type="text/javascript">
// 生成目录索引列表
// ref: http://www.cnblogs.com/wangqiguo/p/4355032.html
// modified by: zzq
function GenerateContentList()
{
    var mainContent = $('#cnblogs_post_body');
    var h2_list = $('#cnblogs_post_body h2');//如果你的章节标题不是h2,只需要将这里的h2换掉即可

    if(mainContent.length < 1)
        return;

    if(h2_list.length>0)
    {
        var content = '<a name="_labelTop"></a>';
        content += '<div >';
        content += '<p style="font-size:18px;"><b>目录</b></p>';
        content += '<ul>';
        for(var i=0; i<h2_list.length; i++)
        {
            var go_to_top = '<div style="text-align: right;"><a href="#_labelTop" style="color:#f68a33">Top</a><a name="_label' + i + '"></a></div>';
            $(h2_list[i]).before(go_to_top);

            var h3_list = $(h2_list[i]).nextAll("h3");
            var li3_content = '';
            for(var j=0; j<h3_list.length; j++)
            {
                var tmp = $(h3_list[j]).prevAll('h2').first();
                if(!tmp.is(h2_list[i]))
                    break;
                var li3_anchor = '<a name="_label' + i + '_' + j + '"></a>';
                $(h3_list[j]).before(li3_anchor);
                li3_content += '<li><a href="#_label' + i + '_' + j + '">' + $(h3_list[j]).text() + '</a></li>';
            }

            var li2_content = '';
            if(li3_content.length > 0)
                li2_content = '<li><a href="#_label' + i + '">' + $(h2_list[i]).text() + '</a><ul>' + li3_content + '</ul></li>';
            else
                li2_content = '<li><a href="#_label' + i + '">' + $(h2_list[i]).text() + '</a></li>';
            content += li2_content;
        }
        content += '</ul>';
        content += '</div><p> </p>';
        content += '<hr style="height:1px;border:none;border-top:1px dashed #0066CC;"/>';
        if($('#cnblogs_post_body').length != 0 )
        {
            $($('#cnblogs_post_body')[0]).prepend(content);
        }
    }
}

GenerateContentList();
</script>

四 在文章右上角添加目录导航

此方法是纯搬运的:原地址

1. 申请开通js权限

2. 添加css代码到“页面定制CSS代码”

博客园生成目录
博客园生成目录

/*生成博客目录的CSS*/
#uprightsideBar{
    font-size:12px;
    font-family:Arial, Helvetica, sans-serif;
    text-align:left;
    position:fixed;/*将div的位置固定到距离top:50px,right:0px的位置,这样div就会处在最右边的位置,距离顶部50px*/
    top:50px;
    right:0px;
     auto;
    height: auto; 
}
#sideBarTab{
    float:left;
    30px; 
    border:1px solid #e5e5e5;
    border-right:none;
    text-align:center;
    background:#ffffff;
}

#sideBarContents{
    float:left;
    overflow:auto; 
    overflow-x:hidden;!important;
    200px;
    min-height:108px;
    max-height:460px;
    border:1px solid #e5e5e5;
    border-right:none; 
    background:#ffffff;
}
#sideBarContents dl{
    margin:0;
    padding:0;
}

#sideBarContents dt{
    margin-top:5px;
    margin-left:5px;
}

#sideBarContents dd, dt {
    cursor: pointer;
}

#sideBarContents dd:hover, dt:hover {
    color:#A7995A;
}
#sideBarContents dd{
    margin-left:20px;
}

3. 添加js脚本到“页首Html代码”

博客园生成目录
博客园生成目录

<script type="text/javascript">
/*
    功能:生成博客目录的JS工具
    测试:IE8,火狐,google测试通过
    孤傲苍狼
    2014-5-11
*/
var BlogDirectory = {
    /*
        获取元素位置,距浏览器左边界的距离(left)和距浏览器上边界的距离(top)
    */
    getElementPosition:function (ele) {        
        var topPosition = 0;
        var leftPosition = 0;
        while (ele){              
            topPosition += ele.offsetTop;
            leftPosition += ele.offsetLeft;        
            ele = ele.offsetParent;     
        }  
        return {top:topPosition, left:leftPosition}; 
    },

    /*
    获取滚动条当前位置
    */
    getScrollBarPosition:function () {
        var scrollBarPosition = document.body.scrollTop || document.documentElement.scrollTop;
        return  scrollBarPosition;
    },
    
    /*
    移动滚动条,finalPos 为目的位置,internal 为移动速度
    */
    moveScrollBar:function(finalpos, interval) {

        //若不支持此方法,则退出
        if(!window.scrollTo) {
            return false;
        }

        //窗体滚动时,禁用鼠标滚轮
        window.onmousewheel = function(){
            return false;
        };
          
        //清除计时
        if (document.body.movement) { 
            clearTimeout(document.body.movement); 
        } 

        var currentpos =BlogDirectory.getScrollBarPosition();//获取滚动条当前位置

        var dist = 0; 
        if (currentpos == finalpos) {//到达预定位置,则解禁鼠标滚轮,并退出
            window.onmousewheel = function(){
                return true;
            }
            return true; 
        } 
        if (currentpos < finalpos) {//未到达,则计算下一步所要移动的距离
            dist = Math.ceil((finalpos - currentpos)/10); 
            currentpos += dist; 
        } 
        if (currentpos > finalpos) { 
            dist = Math.ceil((currentpos - finalpos)/10); 
            currentpos -= dist; 
        }
        
        var scrTop = BlogDirectory.getScrollBarPosition();//获取滚动条当前位置
        window.scrollTo(0, currentpos);//移动窗口
        if(BlogDirectory.getScrollBarPosition() == scrTop)//若已到底部,则解禁鼠标滚轮,并退出
        {
            window.onmousewheel = function(){
                return true;
            }
            return true;
        }
        
        //进行下一步移动
        var repeat = "BlogDirectory.moveScrollBar(" + finalpos + "," + interval + ")"; 
        document.body.movement = setTimeout(repeat, interval); 
    },
    
    htmlDecode:function (text){
        var temp = document.createElement("div");
        temp.innerHTML = text;
        var output = temp.innerText || temp.textContent;
        temp = null;
        return output;
    },

    /*
    创建博客目录,
    id表示包含博文正文的 div 容器的 id,
    mt 和 st 分别表示主标题和次级标题的标签名称(如 H2、H3,大写或小写都可以!),
    interval 表示移动的速度
    */
    createBlogDirectory:function (id, mt, st, interval){
         //获取博文正文div容器
        var elem = document.getElementById(id);
        if(!elem) return false;
        //获取div中所有元素结点
        var nodes = elem.getElementsByTagName("*");
        //创建博客目录的div容器
        var divSideBar = document.createElement('DIV');
        divSideBar.className = 'uprightsideBar';
        divSideBar.setAttribute('id', 'uprightsideBar');
        var divSideBarTab = document.createElement('DIV');
        divSideBarTab.setAttribute('id', 'sideBarTab');
        divSideBar.appendChild(divSideBarTab);
        var h2 = document.createElement('H2');
        divSideBarTab.appendChild(h2);
        var txt = document.createTextNode('目录导航');
        h2.appendChild(txt);
        var divSideBarContents = document.createElement('DIV');
        divSideBarContents.style.display = 'none';
        divSideBarContents.setAttribute('id', 'sideBarContents');
        divSideBar.appendChild(divSideBarContents);
        //创建自定义列表
        var dlist = document.createElement("dl");
        divSideBarContents.appendChild(dlist);
        var num = 0;//统计找到的mt和st
        mt = mt.toUpperCase();//转化成大写
        st = st.toUpperCase();//转化成大写
        //遍历所有元素结点
        for(var i=0; i<nodes.length; i++)
        {
            if(nodes[i].nodeName == mt|| nodes[i].nodeName == st)    
            {
                //获取标题文本
                var nodetext = nodes[i].innerHTML.replace(/</?[^>]+>/g,"");//innerHTML里面的内容可能有HTML标签,所以用正则表达式去除HTML的标签
                nodetext = nodetext.replace(/ /ig, "");//替换掉所有的 
                nodetext = BlogDirectory.htmlDecode(nodetext);
                //插入锚        
                nodes[i].setAttribute("id", "blogTitle" + num);
                var item;
                switch(nodes[i].nodeName)
                {
                    case mt:    //若为主标题 
                        item = document.createElement("dt");
                        break;
                    case st:    //若为子标题
                        item = document.createElement("dd");
                        break;
                }
                
                //创建锚链接
                var itemtext = document.createTextNode(nodetext);
                item.appendChild(itemtext);
                item.setAttribute("name", num);
                item.onclick = function(){        //添加鼠标点击触发函数
                    var pos = BlogDirectory.getElementPosition(document.getElementById("blogTitle" + this.getAttribute("name")));
                    if(!BlogDirectory.moveScrollBar(pos.top, interval)) return false;
                };            
                
                //将自定义表项加入自定义列表中
                dlist.appendChild(item);
                num++;
            }
        }
        
        if(num == 0) return false; 
        /*鼠标进入时的事件处理*/
        divSideBarTab.onmouseenter = function(){
            divSideBarContents.style.display = 'block';
        }
        /*鼠标离开时的事件处理*/
        divSideBar.onmouseleave = function() {
            divSideBarContents.style.display = 'none';
        }

        document.body.appendChild(divSideBar);
    }
    
};

window.onload=function(){
    /*页面加载完成之后生成博客目录*/
    BlogDirectory.createBlogDirectory("cnblogs_post_body","h2","h3",20);
}
</script>

4. 效果如下:

博客园生成目录
博客园生成目录