【はてなブログ】目次が動作しないエラーを解決した。
目次を挿入してみたら、目次が動かないことが判明した。
目次の章タイトルをクリックしても、なんの変化もなく、全く遷移してくれないのである。目次が動かないなんて、さて困った。
理由は、見出しをスクリプトにて強制変換していたからであった。大見出し(h3)をh2に、中見出し(h4)をh3に、小見出し(h5)をh4に強制変換しているように設定していたため、内部リンクがうまく作動せずに、全く遷移しないのであろう。
参考:【はてなブログ】大見出しをh3からh2に変更した。 - 傷鴨日記
したがって、これを何とかしないことには目次が動作してくれない。
で、解決策はあっさり出てきた(ググってもなかなか出てこなかったけど)。
見出し強制変換スクリプトを変更するのである。以下の記事にあるコードに書き換えれば、目次も問題なく動いた。
以下のコードを『デザイン』→『カスタマイズ』→『フッタ』欄に貼り付ける。
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script> <script> $(function(){ if (!document.querySelector('.entry-content h2')){ $('.entry-content h3').replaceWith(function() { var tag_class_h3 = $(this).attr("class"); var tag_id_h3 = $(this).attr("id"); if ( tag_class_h3 == null) { var tag_class_plus_h3 =[]; } else { var tag_class_plus_h3 = 'class="'+tag_class_h3+'"'; } if ( tag_id_h3 == null ) { var tag_id_plus_h3 =[]; } else { var tag_id_plus_h3 = 'id="'+tag_id_h3+'"'; } $(this).replaceWith('<h2 '+tag_id_plus_h3+' '+tag_class_plus_h3+'>'+$(this).html()+'</h2>'); }); $('.entry-content h4').replaceWith(function() { var tag_class_h4 = $(this).attr("class"); var tag_id_h4 = $(this).attr("id"); if ( tag_class_h4 == null) { var tag_class_plus_h4 =[]; } else { var tag_class_plus_h4 = 'class="'+tag_class_h4+'"'; } if ( tag_id_h4 == null ) { var tag_id_plus_h4 =[]; } else { var tag_id_plus_h4 = 'id="'+tag_id_h4+'"'; } $(this).replaceWith('<h3 '+tag_id_plus_h4+' '+tag_class_plus_h4+'>'+$(this).html()+'</h3>'); }); $('.entry-content h5').replaceWith(function() { var tag_class_h5 = $(this).attr("class"); var tag_id_h5 = $(this).attr("id"); if ( tag_class_h5 == null) { var tag_class_plus_h5 =[]; } else { var tag_class_plus_h5 = 'class="'+tag_class_h5+'"'; } if ( tag_id_h5 == null ) { var tag_id_plus_h5 =[]; } else { var tag_id_plus_h5 = 'id="'+tag_id_h5+'"'; } $(this).replaceWith('<h4 '+tag_id_plus_h5+' '+tag_class_plus_h5+'>'+$(this).html()+'</h4>'); }); } }); </script>
これで見出しも強制変換されて、かつ目次もきちんと動作した。