一段 JS 代码让 Markdown 自动生成目录

2014-11-03 17:07:57 +08:00
 yanleijava

文章来自:一段JS代码让Markdown自动生成目录

前言

已经习惯了使用Markdown书写文章,既方便也通用。

但一直在想:应该生成一个方便的导航目录,这样查看文章会更方便。于是有了本文。

实现方法

页面结构

//放入在文章页内容前面
<div class="BlogAnchor">
    <p>
        <b id="AnchorContentToggle" title="收起" style="cursor:pointer;">目录[-]</b>
    </p>
    <div class="AnchorContent" id="AnchorContent"> </div>
</div>

Js代码

//在文章中查找title并填充到div AnchorContent中
$(".post-content").find("h2,h3,h4,h5,h6").each(function(i,item){
    var tag = $(item).get(0).localName;
    $(item).attr("id","wow"+i);
    $("#AnchorContent").append('<li><a class="new'+tag+' anchor-link" onclick="return false;" href="#" link="#wow'+i+'">'+(i+1)+" · "+$(this).text()+'</a></li>');
    $(".newh2").css("margin-left",0);
    $(".newh3").css("margin-left",20);
    $(".newh4").css("margin-left",40);
    $(".newh5").css("margin-left",60);
    $(".newh6").css("margin-left",80);
});
$("#AnchorContentToggle").click(function(){
    var text = $(this).html();
    if(text=="目录[-]"){
        $(this).html("目录[+]");
        $(this).attr({"title":"展开"});
    }else{
        $(this).html("目录[-]");
        $(this).attr({"title":"收起"});
    }
    $("#AnchorContent").toggle();
});

CSS代码

/*导航*/
.BlogAnchor {
    background: #f4f7f9;
    padding: 10px;
    line-height: 180%;
}
.BlogAnchor p {
    font-size: 18px;
    color: #15a230;
    margin-bottom: 0.3em;
}
.BlogAnchor .AnchorContent {
    padding: 5px 0px;
}
.BlogAnchor li{
    text-indent: 20px;
    font-size: 14px;
}
#AnchorContentToggle {
    font-size: 13px;
    font-weight: normal;
    color: #FFF;
    display: inline-block;
    line-height: 20px;
    background: #5cc26f;
    font-style: normal;
    padding: 1px 8px;
    margin-right: 10px;
}
.BlogAnchor a:hover {
    color: #5cc26f;
}
.BlogAnchor a {
    text-decoration: none;
}

导航扩展

同时也可以实现锚点之间的平滑滚动,使用jquery animate

$(".anchor-link").click(function(){
    $("html,body").animate({scrollTop: $($(this).attr("link")).offset().top}, 1000);
});

具体效果参考本文

文章来自:一段JS代码让Markdown自动生成目录

5182 次点击
所在节点    程序员
6 条回复
kimmykuang
2014-11-03 17:17:31 +08:00
LZ你贴的链接不对哦,贴成admin后台的链接了
yanleijava
2014-11-03 17:19:41 +08:00
bitbegin
2014-11-03 18:06:26 +08:00
不同的渲染工具有同样的效果码?
yanleijava
2014-11-03 18:51:14 +08:00
@bitbegin 效果都是CSS控制,一样的
yijian166
2014-11-03 21:55:49 +08:00
https://github.com/yijian166/md-toc.js 哈哈,自己也写了一个,不依赖任何js库,支持点击跳转~~
yanleijava
2014-11-04 10:15:00 +08:00
@yijian166 不错

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/143661

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX