给博客添加文章目录

2018-07-08  本文已影响353人  hojun
image

前言

因为JSimple主题没有自带目录,所以需要自己动手给hexo博客文章添加目录功能。

第一步 查阅hexo文档

在Hexo官网 文档>自定义>辅助函数>最下面,可以找到toc这个函数,看其介绍能知道它就是来实现文章目录的。

image

第二步 决定目录位置

根据博客浏览文章的页面,决定将目录放在右上角空白处。


image

第三步 编写主题模板

首先,找到文章模板页面,博主这里是在\themes\jsimple\layout_widget\common-article.ejs这个文件中,插入需要的代码。(因为toc需要post变量,所以我们把post传入)


image

这里博主采用的是局部模板和局部变量,把目录当成一块独立的组件分离了出去。(你也可以不用分离,直接在当前文件中写详细的代码)


image
既然用到了局部模板,我们就要新建一个toc.ejs的模板,其中插入的代码如下:
<aside id="article-toc" role="navigation" class="fixed">
    <div id="article-toc-inner">
        <strong class="sidebar-title">
        目录</strong>
        <%- toc(post.content, {list_number: false}) %>
    </div>
</aside>

其中,list_number: false表示目录不显示编号。
出来html标签,我们还需要css样式来布局目录的位置大小等。
css如下:

#article-toc-inner:after,#article-toc-inner:before,.inner:after,.inner:before {
    content: "";
    display: table
}

#article-toc-inner:after,.inner:after {
    clear: both
}

@media screen {
    #article-toc-inner,.inner {
        padding: 0 20px
    }
}
#article-toc {
    display: none;
    float: right;
    width: 25%;
    margin-right: -220px;
    opacity: .8
}
@media screen and (min-width:769px) {
    #article-toc {
        display: block
    }
}
#article-toc.fixed {
    position: absolute;
    top: 0;
    bottom: 0;
    right: 220px;
    padding-top: 55px;
}
.fixed #article-toc-inner {
    position: fixed;
    width: 220px;
    top: 0;
    bottom: 0;
    padding-top: 55px;
}
#article-toc-inner ol {
    margin-left: -16px;
}

将css引入页面即可。

效果预览

image
上一篇 下一篇

猜你喜欢

热点阅读