给博客园文章添加目录

FLowUs邀请链接:https://flowus.cn/login?code=AXNU63
FlowUs邀请码:AXNU63


将下面的代码粘贴到页脚代码里就行:

<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 id="navCategory" style="color:#152e97;">';
        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>&nbsp;</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>
posted @ 2020-01-23 23:26  wbytts  阅读(454)  评论(0编辑  收藏  举报