ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 티스토리 Letter 스킨 자동 목차
    IT-Information/Blog-operation 2024. 5. 10. 01:20

    티스토리의 Letter 스킨에서 자동 목차 기능을 적용해보려고합니다.

     

    Tocbot이라는 라이브러리를 사용해 자동 목차를 생성합니다.

     

    <head></head> 안에 코드 넣기

    head 부분 안에 적용해야 할 것이 2가지 코드가 있습니다.

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

     

    CSS와 js파일을 연결하는 것입니다.

     

    <body></body> 태그 안 <s_permalink_article_rep> 밑 class 추가

    <div class="toc toc-fixed" ></div>

     

    <s_permalink_article_rep> 밑에 위의 구문을 추가합니다.

     

    </body>바로 위에 스크립트 추가

    <script>
      let content = document.querySelector('.article_view')
      let headings = content.querySelectorAll('h1, h2, h3, h4, h5, h6, h7')
      let headingMap = {}
    
      Array.prototype.forEach.call(headings, function (heading) {
          let 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',
        hasInnerContainers: false
      });
    
      $(document).ready(function(){
        $('.toc').addClass('toc-absolute');
    
        let toc_top = $('.toc').offset().top;
        $(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>

    바디 태그가 끝나는 지점 바로 위에 스크립트 구문을 추가해줍니다.

     

    CSS 추가

    /*tocbot*/
    
    .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;
    }
    
    .toc-list-item .is-collapsed{
        max-height: 3000px;

     

    이렇게 작성이 되면 자동 목차가 완료됩니다.

     

    티스토리 Letter 스킨 자동 목차 설정된 모습

     

Designed by Tistory.