11document . addEventListener ( "DOMContentLoaded" , ( ) => {
2+ // 目次内のリンクをすべて取得
23 const tocLinks = document . querySelectorAll ( ".toc a" ) ;
34 if ( tocLinks . length === 0 ) {
45 return ;
56 }
67
8+ // 目次リンクから対応する見出し要素を取得
79 const headings = Array . from ( tocLinks )
810 . map ( ( link ) => {
911 const href = link . getAttribute ( "href" ) ;
@@ -16,11 +18,12 @@ document.addEventListener("DOMContentLoaded", () => {
1618 return ;
1719 }
1820
21+ // IntersectionObserverを初期化して、見出しが画面内に入ったかを監視
1922 const observer = new IntersectionObserver (
2023 ( entries ) => {
2124 let activeHeading = null ;
2225
23- // Find the heading that is intersecting and closest to the top trigger margin
26+ // 画面内に表示されている見出しの中から、最も上にあるものを探す
2427 for ( const entry of entries ) {
2528 if ( entry . isIntersecting ) {
2629 if (
@@ -33,8 +36,7 @@ document.addEventListener("DOMContentLoaded", () => {
3336 }
3437 }
3538
36- // If no heading is currently intersecting within the rootMargin,
37- // find the last one that scrolled past the top of the viewport.
39+ // 画面内に見出しがない場合、最後に通過した見出しをアクティブにする
3840 if ( ! activeHeading ) {
3941 for ( let i = headings . length - 1 ; i >= 0 ; i -- ) {
4042 if ( headings [ i ] . getBoundingClientRect ( ) . top < 0 ) {
@@ -44,26 +46,22 @@ document.addEventListener("DOMContentLoaded", () => {
4446 }
4547 }
4648
47- // Update the active class on all links
49+ // すべての目次リンクのアクティブ状態を更新
4850 tocLinks . forEach ( ( link ) => {
49- if (
51+ const isActive =
5052 activeHeading &&
5153 link . getAttribute ( "href" ) ===
52- `#${ activeHeading . id } `
53- ) {
54- link . classList . add ( "is-active" ) ;
55- } else {
56- link . classList . remove ( "is-active" ) ;
57- }
54+ `#${ activeHeading . id } ` ;
55+ link . classList . toggle ( "is-active" , isActive ) ;
5856 } ) ;
5957 } ,
6058 {
61- // This creates a "trigger zone". An observation entry is created when a
62- // heading enters the area between 20% from the top and 20% from the bottom.
59+ // ビューポートの上部20%から下部80%の範囲で見出しを監視
6360 rootMargin : "-20% 0px -80% 0px" ,
6461 threshold : 0 ,
6562 } ,
6663 ) ;
6764
65+ // すべての見出しを監視対象に追加
6866 headings . forEach ( ( heading ) => observer . observe ( heading ) ) ;
6967} ) ;
0 commit comments