怎么让博客园文章支持生成目录索引

用过markdown的同学都知道,生成目录索引的标签是 [TOC] ,但是博客园markdown编辑器不支持 [TOC] 标签,于是决定自己实现目录索引功能。

1. 实现思路

博客园会把[TOC]标签原样显示出来<p>[TOC]</p>,所以我们可以遍历文章的所有h1、h2、h3标签依次组合成目录列表,然后替换掉<p>[TOC]</p>

2. JS代码

我这里把生成目录功能写成一个jquery插件Catalog,使用的时候直接$( "#cnblogs_post_body" ).catalog(),CSS样式这里就不贴了,大家可以根据自己喜好编写CSS样式。

( function( $ ) {

    function Catalog( element, options ) {
        this.$parentEle = $( element );
        this.$catalog_container = $( "<div>" );
        this.$catalog_title = $( "<h1>" );
        this.$ul_container = $( "<ul>" );
        this.$control_a = $( "<button>" );
        this.titleReg = /^h[1-3]$/;
        this.static = true;
        this.init( this );
    }

    Catalog.prototype = {
        init: function( self ) {
            // 组合目录容器和标题等
            self.$catalog_title.text( '目录' );
            self.$catalog_container.attr( "id", "catalog" )
            .append( self.$catalog_title )
            .append( self.$control_a.attr( "class", "control_btn").text( "-" ) );
            // 查找文章中所有的h1、h2、h3标签
            // 生成目录列表插入目录容器中
            self.$parentEle.children().each( function() {
                if( self.titleReg.test( this.tagName.toLowerCase() ) ) {
                    $( this ).append( "<a href='#catalog' class='title_back'> #</a>" );
                    self.$ul_container.append( self.list( this ) );
                }
            } );
            // 替换[TOC]为目录
            $( "#cnblogs_post_body > p" ).eq(0).replaceWith(self.$catalog_container.append(self.$ul_container));
            // 添加目录收缩功能
            $( "#catalog > button" ).on( "click", function() {
                $( "#catalog ul" ).toggle();
                $( event.target ).text( self.static ? "+" : "-" );
                self.static = !self.static;
            } );
        },

        // 生成目录列表函数
        list: function( element ) {
            var aEle = $( "<a></a>" ),
                hEle = $( "<li></li>" );
            aEle.attr( "href", "#" + element.id ).text( element.childNodes[0].nodeValue );
            hEle.attr( "class", element.nodeName.toLowerCase() + "_list" ).append( aEle );
            return hEle;
        },
    };

    $.fn.catalog = function( options ) {
        return this.each( function() {
            if( !$.data( this, 'catalog' ) ) {
                $.data( this, 'catalog', new Catalog( this, options ) );
            }
        } );
    }

    // 使用插件
    $( "#cnblogs_post_body" ).catalog();

} )( window.jQuery );

基本功能完成了,虽然简单但是能凑合着用。

3. 使用

  • 申请开通JS接口
  • “管理” -> “设置” -> “页脚HTML”,直接把代码拷贝进去。(注意:代码头尾需要加<script></script>标签)
原文地址:https://www.cnblogs.com/roddy/p/6579414.html