【雑記】自動で目次作る機能足してみた

このページはWordpressでできているのですが、このたび自動でh2を集計して目次を作る機能を作ってみました。

目次

今は各ページこんな感じで表示されていると思います。

仕組み

テーマはSimplicityというのを利用していますので、これ専用で作ってます。

もしこれを入れたくてかつ他のテーマの人は適宜書き換えてください。(class名等が違うはずなので)

今回はJavaScriptとcssだけで完結させて、phpは一切触っていません。

JavaScript

jQuery(window).ready(function() {
    var $ = jQuery;
    var createIndex = function(clazz, tag) {
        return '<li><a class="aih-buttons" href="javascript:void(0);" name="aih-' + clazz + '">' + tag + '</a></li>';
    };
    var indices = '';
    var n = 1;
    $('h2').each(function() {
        $('<a>').attr('id', 'aih' + n).insertBefore(this);
        indices += createIndex('aih' + n, $(this).text());
        ++n;
    } );
    indices += createIndex('related-entries', '関連記事');
    indices += createIndex('comment-area', 'コメント');

    var index = $('<div>');
    index.attr('id', 'article-index' );
    index.html('<div id="article-index-header"><a id="article-index-switch" href="javascript:void(0);">▼目次</a></div><div id="article-index-main"><ul id="article-index-list">' + indices + '</ul></div></div>');
    index.insertBefore('#the-content');
    index.ready(function() {
        var toggle = function() {
            var text = ($(this).is(':visible') ? '▲' : '▼') + '目次';
            $('#article-index-switch').text(text);
        };
        $('#article-index-switch').click(function() {
            $('#article-index-main').toggle(300, toggle);
        } );

        $('.aih-buttons').click(function() {
            var target = $(this).attr('name').substr('aih-'.length);
            var  top = $('#' + target).position().top | 0;
               if (top > 16) { top -= 16; }
            $('body,html').animate( { scrollTop: top }, 800);
        } );
    } );
} );

まずJavaScript

h2の前にスクロール先となるaタグを挿入しています。($(h2).eachの部分)

スクロール先の識別にはname属性を利用しています。

<li>の項目がクリックされたら($(‘.aih-buttons’).clickの部分)スクロール先のtopを取得してそこにスクロールするjQueryの命令を呼んでいるだけです。

おまけで、関連記事とコメントも目次に足しています。

CSS

#article-index {
    border-bottom: dashed 3px #ccc;
    margin-bottom: 12px;
    margin-top: 8px;
}

#article-index-list {
    margin-top: 2px;
}

#article-index-main {
    display: none;
}

#article-index-header {
    font-size: 120%;
    font-weight: bold;
}

これは表示を調整しているくらいです。

最初に目次表示されていると邪魔なので#article-index-mainのdisplayはnoneにして初期は非表示にしています。

タイトルとURLをコピーしました