前言
已经习惯了使用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-siz: 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); }); 具体效果参考本文
