ページ内の見出しに合わせて目次を自動生成する

Ads

Result


簡易的なものなので汎用性は高くは無いかも。

jQuery

(function($) {
    $.fn.toc = function(o, p) {
        p = $.extend({
            title: "タイトル"
        }, p);
        //見出しを入れるボックスを生成
        this.prepend('<div id="toc-list"><strong>' + p.title + '</strong><ol></ol></div>').children(o).each(function(i) {
            i = i + 1;
       //IDを合わせて見出しへのページ内リンクと目次へのページ内リンクを生成
            $(this).attr('id', 'section-' + i).nextUntil(o).after('<a href="#toc-list">Topへ &uArr;</a>');
            $('<li><a href="#section-' + i + '">' + $(this).text() + '</a></li>').appendTo('#toc-list ol');
        });
    };
})(jQuery);
$(function() {
    $('article').toc('h3', {//目次にする要素を指定
        title: "目次:"
    });
});

アニメーションさせる場合は更に以下を書く。

$('#toc-list a, a[href="#toc-list"]').on("click", function() {
        var hash = this.hash;
        $('html,body').animate({scrollTop: $(hash).offset().top}, 600, function() {
            window.location.hash = hash;
        });
        return false;
    });

css

#toc-list {/*見出しのボックス*/
    width:60%;
    border:1px solid #ccc;
    background-color:#efefef;
    padding:5px 10px 5px 15px;
}

h3:target {/*見出しへのページ内リンクが押されたときの見出しのスタイル*/
    padding:10px 15px;
}

html

<article>
    <h3>Header 01</h3>
    <p>text text text text text text text text text text </p>
    
    <h3>Header 02</h3>
    <p>text text text text text text text text text text </p>
 
        <h3>Header 03</h3>
    <p>text text text text text text text text text text </p>
</article>

via

via:http://www.dte.web.id/2012/07/simple-auto-table-of-content-plugin-1.html#.USYkiaXxoy0

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