使用tocbot给自动文章添加目录

使用tocbot给自动文章添加目录

引入文件

<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.5.0/tocbot.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.5.0/tocbot.css">

给markdown生成的html里的所有h标签生产自己的id属性值

  var headerEl = 'h1,h2,h3,h4',  //headers
    content = '.article-content',//文章容器
    idArr = {
    
    };  //标题数组以确定是否增加索引id
//add #id

$(content).children(headerEl).each(function () {
    
    
    //去除空格以及多余标点
    var headerId = $(this).text().replace(/[\s|\~|`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\_|\+|\=|\||\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?|\:|\,|\。]/g, '');

    headerId = headerId.toLowerCase();
    if (idArr[headerId]) {
    
    
        //id已经存在
        $(this).attr('id', headerId + '-' + idArr[headerId]);
        idArr[headerId]++;
    }
    else {
    
    
        //id未存在
        idArr[headerId] = 1;
        $(this).attr('id', headerId);
    }
});

初始化tocbot

tocbot.init({
    
    
            {
    
    #添加到哪里#}
            tocSelector: '.tocContainer',
            {
    
    #针对那个id标签#}
            contentSelector: '.article-content',
            {
    
    #滚动跟随#}
            positionFixedClass: 'is-position-fixed',
            positionFixedSelector: '.aside-article-catalog',
            {
    
    #// 需要解析的标题#}
            headingSelector: headerEl,
        });

猜你喜欢

转载自blog.csdn.net/qq_31910669/article/details/114703845
今日推荐