Tocbot自动目录
1.引入Tocbot相关的文件
在侧边公告栏,输入如下代码:
<!--Tocbot目录-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.css">
<!--此处的div.toc 用来存放Tocbot生成的目录-->
<div class="toc"></div>
2.为每一个标题生成唯一的id
<script language="javascript" type="text/javascript">
var id = 1;
// blogpost-body 为正文容器的 class,根据自己的情况修改
$(".blogpost-body").children("h1,h2,h3,h4,h5").each(function () {
// 使用中文 id ,注意非ANSI编码文字会导致无法跳转
//var hyphenated = $(this).text().replace(/\s/g, '-');
// 英文id
var hyphenated = "myunique-" + id;
$(this).attr('id', hyphenated);
id++;
});
</script>
3.初始化Tocbot
<script language="javascript" type="text/javascript">
tocbot.init({
// Where to render the table of contents.
// 放置目录的容器,此处toc与步骤1 div的类名保持一致
tocSelector: '.toc',
// Where to grab the headings to build the table of contents.
// 正文内容所在位置,可以通过F12进行查看
contentSelector: '.blogpost-body',
// Which headings to grab inside of the contentSelector element.
// 需要索引的标题级别
headingSelector: 'h1, h2, h3, h4, h5',
//目录位置固定
positionFixedSelector: ".toc",
//回调函数
scrollEndCallback: function (e) {
//修正滚动后页面的位置,80 是自己顶部栏的高度
window.scrollTo(window.scrollX, window.scrollY - 80);
},
});
</script>
4.保存,刷新即可看到目录
5.设置样式
根据自己的需求自定义样式
/*toc目录*/
.toc {
width: 200px;
height: auto;
z-index: 98;
background-color: rgba(255,255,255,0);
transform: translateX(0);
right: 25%;
position: fixed !important;
top:480px;
position: absolute;
padding-top: 10px;
padding-bottom: 10px;
}