FE

Tistory #1 스킨에서 TOC(table-of-contents) 적용하기

개발자 뭄뭄 2023. 3. 22. 08:50
반응형

N2T를 잘 사용하고 있던 중, N2T 프로그램을 개발하신 minimin2 님의 블로그 글 오른쪽에는 목차가 나오는 것을 확인했다! 너무너무 부러워서 나도 적용하고 싶은데~ 하고 검색하다가 잘 안돼서 좌절 중이었다 (ㅜㅜ)

그러다 오늘 성공해서 추후의 나 & 다른 사람을 위해서 적는 글

참고로 이 글은 tistory의 #1 스킨을 기준으로 작성되었다.

이제 나도 글 오른쪽에 귀여운 toc 가 생겼다구요~

1. 스킨 > html 편집모드로 들어가기

2. Tocbot 로드하기

<head> </head> 사이에 아래 코드를 추가해 준다.


<!-- 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 -->

3. body 안에 tocbot 위치시키기

Ctrl + F를 이용해서 <s_permalink_article_rep> 태그를 찾고. 바로 아랫부분에 toc 을 추가한다

// <s_permalink_article_rep> 바로 하단에 추가

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

4. JavaScript 수정하기

</body> 태그가 끝나기 전 바로 윗부분 javascript 부분에 해당코드를 추가한다.

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

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

    let 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 수정하기

/*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;}

저장하면 잘 적용되어 있는 것을 확인해 볼 수 있다!


Uploaded by N2T

반응형