しろかい!

アプリ開発や機械学習などの開発Tips.

本文の上部(<!-- more -->の直下)に目次を表示させました

最近見出しの多い記事を書くことが増えてきたので,しろかい!でもエントリの上部に目次を表示させるようにしてみました.
その時に利用したソースコードを紹介します.

f:id:shun9167:20150121174647p:plain

参考にした記事

以下の記事を参考にしました.
はてなブログに記載されているコードを埋め込めば,普通に記事を書くだけで自動的に見出しが表示されるようになります!
(過去に書いた記事にも表示されるようになります)

「続きを読む」の直下に表示するようにする

上記の記事のままのコードだと,目次は本文の最上部に表示されます.
しろかい!では「続きを読む」,すなわち<!-- more -->の直下に表示させたかったので,以下の部分を改良しました.

改良前

if ($(".entry-content h3").length >= 2){
  $("<div class='sectionList'><h3>目次</h3><ol>" + list + "</ol></div>").prependTo(".entry-content");
}

改良後

if ($(".entry-content h3").length >= 2) {
  $(".entry-content p:first").after("<div class='sectionList'><h3>目次</h3><ol>" + list + "</ol></div>");
}

上記コードは,厳密には「.entry-content内の最初の</p> の後に目次を表示」します.
「続きを読む」の前では段落が1つしか存在しないことが前提になっているので気をつけてください.

おまけ:CSS

CSSも晒しておきます.

article .entry-content .sectionList {
    background: #fafafa;
    margin: 0;
    padding: 15px;
    border: 1px solid #ccc;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
}
article .entry-content .sectionList h3 {
    font-size: 110%;
    margin: 0;
}
article .entry-content .sectionList ol {
    margin: 10px 0 0;
    padding: 0 0 0 1.5em;
    list-style: decimal;
}
article .entry-content .sectionList a, article .entry-content .sectionList ol  {
    color:#444;
}
article .entry-content .sectionList a:hover, article .entry-content .sectionList a:focus {
    color:#888;
}