etc./Tistory

[Tistory] 자동 목차 TOC 추가

HelloJinny 2023. 7. 4. 15:59
  <!-- tocbot --> 
  <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 -->
                  <!-- TOC -->
                  <div class='toc toc-fixed'></div>

                  <!-- 에디터 영역 -->
  <!-- TOC -->
  <script> 
    // set heading id 
    function makeHeading(headings){ 
      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; } 
      }); 
    } 
    var headingMap = {}; 
    var headings = document.querySelector('.article-view').querySelectorAll('h1, h2, h3');
    makeHeading(headings); 
    document.addEventListener("DOMContentLoaded", function() {
      // toc addon
    tocbot.init({ 
      // Where to render the table of contents. 
      tocSelector: '.toc', 
      // Where to grab the headings to build the table of contents.
      contentSelector: '.article-view', 
      // Which headings to grab inside of the contentSelector element. 
      headingSelector: 'h1, h2, h3', 
      // For headings inside relative or absolute positioned containers within content. 
      hasInnerContainers: false
      }); 
    });

    $("div.toc.toc-fixed").hide(0);
    $(window).scroll(function() { 
      if (Math.round( $(window).scrollTop()) > 200) { 
        $("div.toc.toc-fixed").show(250);
      } else { 
        $("div.toc.toc-fixed").hide(250);
      } 
    }); 
  </script>
</body>
/* TOC */
.toc-absolute {
    position: absolute;
    margin-top:165px;
}

.toc-fixed {
    position: fixed;
    top: 60px;
}

.toc {
    right: calc((100% - 850px) / 2 - 330px);
    width: 200px;
    padding: 10px;
    box-sizing: border-box;
}
 
.toc-list {
    margin-top: 10px !important;
    font-size: 0.9em;
}
 
.toc > .toc-list li {
    margin-bottom: 8px;
}
 
.toc > .toc-list li:last-child {
    margin-bottom: 0;
}
 
.toc > .toc-list li a {
    text-decoration: none;
}

 

🔗 참고

 

 

티스토리 플로팅 자동 목차 기능 TOC 추가 (오디세이 Odyssey skin)

오늘 티스토리 블로그 글을 작성하면서 목차를 꼭 넣고 싶었는데, 파일을 추가해도 안되고, css 파일을 수정해도 안되고 하다하다가 지쳐서 그만 포기할까 싶던 찰나! 'Growth records'님의 블로그 글

brasseebrassee.tistory.com