为Ghost博客文章添加目录

引入JS文件

在default.hbs中引入js文件,下载TOC

//放在jQuery之后
<script src="https://xxxxxx.com/jquery.toc.min.js"></script>  
添加DIV

在post.hbs文件的</main>标签之前添加下面代码

<aside id="toc">  
    <h4>文章目录</h4>
</aside>  
设置样式

在博客的css文件里设置样式,代码如下:

#toc {
    font: 400 16px/1.8 "Open Sans","Hiragino Sans GB","Microsoft YaHei","WenQuanYi Micro Hei",sans-serif;
    position: fixed;
    display: none;
    left:50%;
    top: 50%;
    width: 180px;
    max-height: 100%;
    padding: 0 5px;
    overflow-y: auto;
}
#toc ol {
    margin: 0 0 0 1em;
    list-style: none;
    padding: 0;
}
#toc li {
    padding: 0;
    position: relative;
}
#toc li:before {
    border: 5px dashed transparent;
    border-left: 5px solid #57a3e8;
    position: absolute;
    left: -1em;
    top: .5em;
}
#toc li:before {
    content: "";
    height: 0;
    width: 0;
    overflow: hidden;
}
#toc a {
    display: block;
    color: #6aa7c0;
    cursor: pointer;
    max-height: 2em;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    text-decoration: none;
    transition: color .3s;
}
#toc a:hover {
    color: #F3A01E;
}
#toc h4 {
    padding-bottom: 0.25em;
    margin: .75em 0;
    border-bottom: 1px solid #b3b3b3;
    font-size: 18px;
    color: #3b3b3b;
    font-family: "Open Sans","Hiragino Sans GB","Microsoft YaHei","WenQuanYi Micro Hei",sans-serif;
}
初始化目录插件并动态的调整样式

在博客下的JS文件中添加下面代码:

$(document).ready(function() {
    //初始化插件
    $('#toc').initTOC({
        selector: "h5, h6",
        scope: "article",
        overwrite: false,
        prefix: "toc"
    });

    //动态设置样式,例如:滚动到一定程度之后隐藏目录
    var mar_left = $(".post").width() / 2 + 20;
    //var top = $("#toc").css("top");  这只能获取类似152px的字符串,下面才能获取值
    //var top = $("#toc").position().top;
    var top = $(window).height();
    $("#toc").css("top",top / 2 - (top / 4)+"px");
    $("#toc ol").html(function(i,origText){
        return origText + "<li><a id='scrollTop' href='#'>返回顶部</a></li>";
    });
    $("#toc").css({"margin-left":mar_left+"px"});
    $(window).scroll(function(){
        var window_offset = $(window).scrollTop();
        var main_header_height = $(".main-header").height();
        var content_height = $(".content").height();
        if(window_offset < main_header_height - 100) {
            $("#toc").hide();
            //下面的条件不能用 a>x>c这种形式,只能用&&.身为一个前端小白表示伤不起...
        }else if(window_offset > main_header_height&&main_header_height+content_height - 500 > window_offset) {
            $("#toc").show();
        }else{
            $("#toc").hide();
        }
    });
});

以上就是我博客的文章目录添加步骤.前端有个好处就是所见即所得,慢慢折腾.^_^

--EOF--