본문 바로가기
티스토리 및 워드프레스/티스토리

[티스토리] 포스팅 목차 자동으로 생성 (ToC) 및 꾸미기

by Physics 2023. 12. 24.
728x90

(Update: 2024-01-13)

티스토리에서 글을 작성할 시, 우리는 대제목, 소제목 등으로 구분하여 글을 작성하며, 이러한 구분들은 구글 SEO가 우리의 글을 평가할 때 좋은 요소가 된다. 이러한 목차들은 html에서 수동으로 직접 만들 수 있지만, 자동으로 매번 목차가 생성될 수 있도록 할 수 있다. 이를 위해서 기본적으로 알아야할 내용들은 아래와 같다.

1. ToC (Table Of Contents) 

• ToC란? 목차, 차레, 순서 등을 나타내는 테이블 
• 자동 목차를 생성함으로써, 
  - 대제목 (<h2> 태그), 중제목 (<h3> 태그)에 대한 목차가 자동으로 생성
  - 해당 제목을 클릭하면 본문의 위치로 자동 이동. 

2. ToC 코드 

2.1. Tocbot

TOC를 만들어주는 tocbot와 관련된 코드를 티스토리 내의 HTML 탭의 <head></head> 태그 안에 넣어준다. 
- 아래의 코드는 tocbot의 script(동작 코드)와 css(기본적인 디자인)를 불러오는 과정 
- 웹 상에서는 클라이언트에서 네트워크 상 빠른 속도를 위해서 압축된 min.js파일을 사용하는 것을 추천 

  <script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.11.1/tocbot.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.11.1/tocbot.css">

- ToCbot URL:  Tocbot (tscanlin.github.io)

2.2 HTML body 부분

아래의 코드를 <div class="content-wrap"> 바로 아래로 붙여넣는다. 
- 아래는 목차의 껍데기를 생성해주는 과정

<!-- TOC 시작 -->
<div class='toc'></div>
<!-- TOC 끝 -->

 

2.3.  Javascript 부분

아래의 코드를 </body> 태그 바로 위에 넣는다.

<!-- TOC 시작 -->
    <script>
    	// Part 1 
        var content = document.querySelector('.entry-content')
        var headings = content.querySelectorAll('h1, h2, h3, h4, h5, h6, h7')
        var headingMap = {}

        // Part 2 
        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
                }
            })
		
        // Part 3 
        tocbot.init({
            tocSelector: '.toc',                   // Where to render the table of contents.
            contentSelector: '.entry-content',     // Where to grab the headings to build the table of contents.
            headingSelector:'h1, h2, h3',          // Which headings to grab inside of the contentSelector element.
            hasInnerContainers: false              // For headings inside relative or absolute positioned containers within content.
        });

        // Part 4
        $(document).ready(function(){
            $('.toc').addClass('toc-absolute');

            var toc_top = $('.toc').offset().top - 165;
            $(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 끝 -->

■ Part 2: 모든 헤더 파일에 unique ID를 생성 

■ Part 3: ToC 초기화 
 - `contentSelector`: 아래의 Note 1 참조 
 - `headingSelector`: ToC로 항목화하고 싶은 헤더들
 - <h2> 태그: 티스토리 내의 제목 1 
 - <h3> 태그: 티스토리 내의 제목 3 

■ Part 4: ToC 항목의 위치
 - Part 4 부분은 Table of Content (ToC)가 스크롤을 할 때 사용자의 스크린을 기준으로 어디에 위치할 지를 결정한다. 
 - 숫자 165는 나중에 나올 CSS 내의 `toc-fixed`의 top 위치이다. 

NOTE 1: 자신이 사용하는 티스토리의 스킨에 따라 위 코드에서 `.entry-content` 을 수정을 해야한다. 현재 내가 사용하는 북스킨의 경우, h1, h2, ..., p, pre, 등과 같은 거의 모든 태그들이 CSS의 `.entry-content` 클래스로 수정이 된다. 반면에 티스토리의 반응형 #2의 경우, `area_view`로 되어있다. 따라서, 자신이 선택한 스킨에 따라 해당 부분을 수정하도록 한다. 

 

3. CSS 코드 

아래의 코드를 CSS 탭 가장 밑에 추가를 한다.

/* TOC */
.toc-absolute {
  position: absolute;
  margin-top: 24px;
}
.toc-fixed {
  position: fixed;
  top: 165px;
}
.toc {
  left: calc((100% - 1020px) / 2 - 250px);
  width: 200px;
  padding: 10px;
  box-sizing: border-box;
}
.toc-list /* 목차의 크기 조절 가능*/
{                             
  margin-top: 14px !important;
  font-size: 0.9em;
}
.toc > .toc-list li {
  margin-bottom: 14px;
}
.toc > .toc-list li:last-child {
  margin-bottom: 0;
}
.toc > .toc-list li a {
  text-decoration: none;
}
.toc-list-item .is-collapsed {
  /*만일 h3 요소가 스크롤시 생략되길 원하면 이 부분은 생략*/	
  max-height: 1000px;
}

 

728x90

댓글