본문 바로가기

Programming/HTMLCSS

티스토리에 TOC(Table of Contents) 목차 만들기

반응형

Toc (Table of Content)가 있다면 전체 포스트의 내용을 한눈에 볼 수 있을 뿐만 아니라,

클릭 한번으로 해당 위치로 이동할 수 있습니다. 자동으로 Toc를 생성해주는 여러가지 오픈소스 라이브러리가 있습니다.

Toc 라이브러리중 Tocbot를 Tistory에 적용하는 방법을 소개합니다.

 

 

1. 준비

https://tscanlin.github.io/tocbot/

 

2. script, css CDN 적용

</head> 바로 위에 아래 코드를 붙여 넣는다.

html
 

 

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

 

3. toc가 표시될 div 추가

본문이 시작되는 부분에 넣습니다.

poster 스킨 기준 <s_permalink_article_rep>를 찾아 그 아래에 붙여 넣으면 됩니다.

html
 
<div class='toc'></div>

 

4. script 작성

</body> 바로 위에 아래 script 작성.

html
 
<script>
  var content = document.querySelector('.entry-content')
  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: '.entry-content',
    headingSelector:'h1, h2, h3',
    hasInnerContainers: false
  });

  $(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>

 

5. css 수정

CSS버튼을 눌러서 CSS 수정 페이지로 이동 후, 아래 코드 입력.

css
 
.toc-absolute {
  position: absolute;
  margin-top:165px;
}
.toc-fixed {
  position: fixed;
  top: 165px;
}

.toc {
  right: calc((100% - 850px) / 2 - 300px);
  width: 250px;
  padding: 10px;
  box-sizing: border-box;
}

.toc-list {
  margin-top: 10px !important;
  font-size: 0.9em;
}

.toc > .toc-list li {
  margin-bottom: 10px;
}

.toc > .toc-list li:last-child {
  margin-bottom: 0;
}

.toc > .toc-list li a {
  text-decoration: none;
}
반응형

'Programming > HTMLCSS' 카테고리의 다른 글

Foodforest 홈페이지 및 로그인 페이지  (0) 2022.04.25
Xml 파일이란 무엇인가?  (0) 2022.04.21
HTML CSS 로 사이트 만들기  (0) 2022.03.17
HTML CSS 연습  (0) 2022.03.17
티스토리 단축키  (0) 2021.12.29