使用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',
content = '.article-content',
idArr = {
};
$(content).children(headerEl).each(function () {
var headerId = $(this).text().replace(/[\s|\~|`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\_|\+|\=|\||\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?|\:|\,|\。]/g, '');
headerId = headerId.toLowerCase();
if (idArr[headerId]) {
$(this).attr('id', headerId + '-' + idArr[headerId]);
idArr[headerId]++;
}
else {
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,
});