在博客园平台为博客自动化添加目录

效果预览

以下示例效果文章的源地址是这篇博客,在完成配置后,在markdown里面的一级标题二级标题等都会在这里的目录中显示,这里仅提供了文章开头目录以及每一个标题中回到顶部的功能,如果需要悬浮窗的目录显示,需要参考其他文章,如这篇博客介绍了小型悬浮窗的效果,但是只能用于二级标题和三级标题的文章。本文的配置方法使用了参考链接1中所给出的方法,效果如下图所示:

操作方案

在设置-页脚HTML代码中添加如下代码:

<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>

版权声明

本文首发链接为:https://www.cnblogs.com/dechinphy/p/toc.html
作者ID:DechinPhy
更多原著文章请参考:https://www.cnblogs.com/dechinphy/

参考链接

  1. https://www.cnblogs.com/douzujun/p/10356169.html
posted @ 2021-03-01 14:10  DECHIN  阅读(158)  评论(0编辑  收藏  举报