-
[티스토리] tocbot을 활용하여 본문에 TOC 목차 넣기기타 2023. 7. 11. 02:46
* 이 글은 HTML/CSS 및 Tistory 환경이 익숙하지 않은 사람을 대상으로 작성되었습니다. 이 글을 잘 따라오신다면, 아래와 같은 TOC를 본문에 배치할 수 있습니다.
0. Pre-requisite
파일 다운로드
파일 업로드
위치: 블로그 설정창 > (좌측 메뉴탭) 꾸미기 > 스킨 편집 > html 편집 > (오른쪽 상단) 파일 업로드
해당 위치에 다운받은 파일을 추가해준다. 반드시 우측 상단에 '적용' 버튼을 눌러야 실제 스킨에 적용이 된다.
1. HTML 수정
위치: 블로그 설정창 > (좌측 메뉴탭) 꾸미기 > 스킨 편집 > html 편집 > HTML
Header 수정
<!-- toc --> <script src="./images/toc.js"></script> <link rel="stylesheet" href="./images/toc.css"> </head>
</head> 태그를 찾아 바로 위에 script, link 태그를 복사해서 붙여넣기 한다.Body 수정
<!-- toc --> <script type="text/javascript"> var content = document.querySelector('.article_view') var headings = content.querySelectorAll('h1, h2, h3, h4, h5, h6, h7') var headingMap = {} Array.prototype.forEach.call(headings, function (heading) { var id = heading.id ? heading.id : heading.textContent.trim().toLowerCase() .split(' ').join('-').replace(/[\!\@\#\$\%\^\&\*\(\):]/ig, '') headingMap[id] = !isNaN(headingMap[id]) ? ++headingMap[id] : 0 if (headingMap[id]) { heading.id = id + '-' + headingMap[id] } else { heading.id = id } }) tocbot.init({ tocSelector: '.toc', contentSelector: '.article_view', headingSelector:'h1, h2, h3, h4', hasInnerContainers: false }); $(document).ready(function(){ $('.toc').addClass('toc-absolute'); var toc_top = $('.toc').offset().top - 10; $(window).scroll(function() { if ($(this).scrollTop() >= toc_top) { $('.toc').addClass('toc-fixed'); $('.toc').removeClass('toc-absolute'); } else { $('.toc').addClass('toc-absolute'); $('.toc').removeClass('toc-fixed'); } }); }); </script> </body>
</body> 태그를 찾아 그 위에 <script> ... </script> 를 붙여넣기 한다.- 표시하고 싶은 목차 위계 범위 설정: 티스토리는 제목1의 위계가 h2로 설정되어 있다.
headingSelector:'h1, h2, h3, h4',
- 사용하는 테마(스킨)에 따라 변경해주어야 하는 부분: Letter 서식은 '.article_view'를 사용한다.
var content = document.querySelector('.article_view') tocbot.init({ tocSelector: '.toc', contentSelector: '.article_view', headingSelector:'h1, h2, h3, h4', hasInnerContainers: false });
본문 수정
조금 까다로울 수 있지만, 본인이 사용하는 테마(스킨)에 따라 태그가 다르기 때문에 검색해서 사용해야 한다. Letter 테마에서는 <s_permalink_article_rep> 가 위치한 곳 바로 뒤에 아래 코드를 붙여넣기 해주면 된다.
<s_permalink_article_rep> <!-- toc --> <div class='toc hidden-xs hidden-sm'></div>
hidden-xs, hidden-sm 를 넣어주면, 모바일 또는 태블릿에서는 설정한 목차(TOC)가 숨겨진다.
제목이 없을 때 목차 TOC 제거하기
</body> 태그 위에 삽입한 <script> ... </script> 를 수정한다. headingMap의 요소가 0개일 때, 'toc' 클래스를 가진 태그를 찾아 제거해준다는 의미의 script로 변경하였다.
<!-- toc --> <script type="text/javascript"> var toc = $('.toc'); var content = document.querySelector('.article_view') var headings = content.querySelectorAll('h1, h2, h3, h4, h5, h6, h7') var headingMap = {} Array.prototype.forEach.call(headings, function (heading) { var id = heading.id ? heading.id : heading.textContent.trim().toLowerCase() .split(' ').join('-').replace(/[\!\@\#\$\%\^\&\*\(\):]/ig, '') headingMap[id] = !isNaN(headingMap[id]) ? ++headingMap[id] : 0 if (headingMap[id]) { heading.id = id + '-' + headingMap[id] } else { heading.id = id } } ) if (Object.keys(headingMap).length) { tocbot.init({ tocSelector: '.toc', contentSelector: '.article_view', headingSelector:'h1, h2, h3, h4', hasInnerContainers: false }); $(document).ready(function(){ toc.addClass('toc-absolute'); var toc_top = toc.offset().top - 10; $(window).scroll(function() { if ($(this).scrollTop() >= toc_top) { toc.addClass('toc-fixed'); toc.removeClass('toc-absolute'); } else { toc.addClass('toc-absolute'); toc.removeClass('toc-fixed'); } }); }); } else { const elements = document.getElementsByClassName('toc'); while(elements.length > 0){ elements[0].parentNode.removeChild(elements[0]); } } </script> </body>
2. CSS 수정
티스토리 CSS 수정
위치: 블로그 설정창 > (좌측 메뉴탭) 꾸미기 > 스킨 편집 > html 편집 > CSS
* CSS의 주석 표시는 /* content */ 만 허용되는 것에 주의한다.
아래의 코드를 해당 위치에 붙여넣기 해준다.
/* toc */ .toc { position: fixed; top: 28%; right: 2.1%; width: 250px; padding: 10px 0px 15px 6px; border-radius: 8px; box-sizing: border-box; box-shadow: 0px 3px 5px rgb(0 0 0 / 35%); background: #59595900; } .toc-list { margin-top: 10px !important; font-size: 14px; padding-right: 8px; /* font-family: "NotoSansKR"; */ color:rgba(63, 63, 63, 0.70); text-overflow:ellipsis; } .toc > .toc-list li { margin-bottom: 10px; } .toc > .toc-list li:last-child { margin-bottom: 0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } .toc > .toc-list li a { text-decoration: none; }
toc.css 파일 수정
TOC 의 scrollbar의 현재 위치 색상을 변경하고 싶을 때
.is-active-link::before { background-color:#3b0132; }
TOC 에서 선택된 / 현재 위치의 목차 리스트 효과를 변경하고 싶을 때
.is-active-link { font-weight:700; color:#050505; } /* Add blinking animation */ .is-active-link { animation: blinker-toc-title 2s linear infinite; } @keyframes blinker-toc-title { 0% { opacity: 0.3; } 50% { opacity: 1.0; } 100% { opacity: 0.3; } }
더보기* 서식을 여러개 선택해서 사용하고 싶을 때,
3. Javascript 수정
서식 파일 업로드
위치: 블로그 설정창 > (좌측 메뉴탭) 콘텐츠 > 서식관리 > 서식쓰기
해당 위치에서 서식을 쓸 때, HTML 모드로 바꾼 후 아래 코드를 복사 붙여넣기 해준다.
<!-- toc --> <script> var content = document.querySelector('.tt_article_useless_p_margin') var headings = content.querySelectorAll('h1, h2, h3, h4, h5, h6, h7') var headingMap = {} Array.prototype.forEach.call(headings, function (heading) { var id = heading.id ? heading.id : heading.textContent.trim().toLowerCase() .split(' ').join('-').replace(/[\!\@\#\$\%\^\&\*\(\):]/ig, '') headingMap[id] = !isNaN(headingMap[id]) ? ++headingMap[id] : 0 if (headingMap[id]) { heading.id = id + '-' + headingMap[id] } else { heading.id = id } }) tocbot.init({ tocSelector: '.toc', contentSelector: '.tt_article_useless_p_margin', headingSelector:'h1, h2, h3', hasInnerContainers: false }); $(document).ready(function(){ $('.toc').addClass('toc-absolute'); var toc_top = $('.toc').offset().top - 10; $(window).scroll(function() { if ($(this).scrollTop() >= toc_top) { $('.toc').addClass('toc-fixed'); $('.toc').removeClass('toc-absolute'); } else { $('.toc').addClass('toc-absolute'); $('.toc').removeClass('toc-fixed'); } }); }); </script>
여기까지 설정했으면, 처음에 보여진 이미지와 같은 TOC가 설정된다. TOC 스타일을 바꾸고 싶으면, CSS 부분에서 자유롭게 수정해서 사용하면 된다.
참조:
https://seons-dev.tistory.com/entry/티스토리-본문에-TOC-목차-넣기(티스토리) 본문에 TOC 목차 넣기
Toc toc 란 toc는 table of contents를 의미하고, markdown으로 작성한 글의 header를 모아서 보여주는 용도로 사용됩니다. 제가 적용한 toc는 tocbot이고, 기본 스타일도 깔끔하지만 제 블로그 스킨에 맞게 CSS
seons-dev.tistory.com
https://guiyomi.tistory.com/136
[티스토리 블로그 테마] - 2. 티스토리 본문에 목차 추가
오늘은 티스토리 블로그 글 상세 페이지에 목차를 추가해보자. 기본 제공 티스토리 테마는 보다시피 본문 목차가 없다. 구글링을 해보니 jQuery의 toc 라이브러리로 간단하게 목차를 생성하는 방
guiyomi.tistory.com