본문 바로가기

블로그 꾸미기

티스토리 플로팅 목차 만들기

목차

  1. 티스토리 HTML 편집
  2. HTML에 tocbot 적용
  3. CSS 적용
  4. 완성

티스토리에서는 기본적으로 제공하는 목차가 없어요,,

그렇기 때문에 직접 만드는 수 밖에는 없습니다. ㅠㅠ

그러나 다행히도 HTML 제목을 가지고 목차를 쉽게 만들 수 있도록 tocbot이라는 것이 있습니다!

tocbot을 이용해 매우 간단하게 플로팅 버튼을 만들어보겠습니다.

 

1. 티스토리 HTML 편집

티스토리 관리자 페이지 메뉴

티스토리 블로그 관리자 페이지 -> 스킨편집을 눌러줍니다.

그리고 HTML 편집버튼을 눌러서 HTML과 CSS를 변경해줄겁니다.

2. HTML에 tocbot 적용

1. </head> 위쪽에 tocbot을 추가해줍니다. (2023.05.21 기준 4.18.2 버전이 최신이네요.)

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

2. <s_permalink_article_rep> 아래에 div toc 태그를 추가해줍니다.

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

3.</body> 위에 아래 코드를 넣어줍니다.

<body>
<!-- toc script start-->
<script>
  var content = document.querySelector('.article_view') // 스킨마다 다름. 무엇을 적을 진 아래에 써놨습니다!
  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: '.article_view', // 스킨마다 다름. 무엇을 적을 진 아래에 써놨습니다!
    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>
<!-- toc script end-->
</body>

주의할 점은 티스토리 스킨마다 본문 div class가 다를 수 있으므로

article_rep_desc 를 감싸고 있는 div class 명으로 바꿔주어야 합니다.

 

3. 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: 1.1em;
}

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

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

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

 

4. 완성

반응형