코딩하거나 논문 읽으면서 다양한 블로그를 방문하게 되는데 가끔, 플로팅 목차가 스크롤을 따라다니는 것을 봤고 언젠가 나도 적용해야지..! 하다가 이제야 적용했다.
확실히 전체적으로 어떤 내용인지 한 눈에 볼 수도 있고, 원하는 컨텐츠로 바로 이동할 수 있어서 좋은 것 같다.
티스토리 블로그에서 사람들이 가장 많이 적용하는 tocbot을 이용했는데, html과 css를 간단하게 수정하면 되기 때문에 쉽게 적용할 수 있는 것 같다.
(#2 스킨 기준으로 설명)
HTML
head
<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">
head가 끝나기 전에 위의 두 줄을 추가해준다. (tocbot의 json 파일과 css 파일을 이용하기 위해서)
body
그 후, body 부분에서 [code]<s_permalink_article_rep>[/code] 부분 아래에 [code]<div class="toc hidden-xs hidden-sm toc-fixed"></div>[/code]를 추가해준다.
...
<s_permalink_article_rep>
<div class="toc hidden-xs hidden-sm toc-fixed"></div>
...
[code]hidden-xs[/code]와 [code]hidden-xm[/code] 모바일 버전에서 보이지 않도록 추가해주었다. (생략해도 상관없음)
그 다음, 아래 코드를 body가 끝나기 직전에 추가해준다.
<script>
let content = document.querySelector('.area_view')
let headings = content.querySelectorAll('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: '.area_view',
headingSelector:'h2, h3, h4',
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');
}
});
tocbot.refresh();
});
</script>
사실 이부분에서 애를 많이 먹었는데, 다른 사람들의 글을 보고 그대로 진행을 했는데도 현재 글의 부분과 toc에 표시된 부분이 맞지 않았다. 그래서 공식 github를 보니 refresh() 라는 것이 있어서 추가해주었더니 잘 동작하였다.
대부분의 블로그에서는 [code]tocbot.refresh()[/code]가 없는 버전의 코드이던데 한 번 저 코드 라인을 지워보고 동일한 문제가 발생한다면 그 때 추가해도 괜찮을 것 같다.
또한, 개인적으로는 위의 코드대로면 목차가 살짝 어색한 것 같아서 scrollTop과 toc_top을 비교하는 부분을 다 날리고, [code]$('.toc').addClass('toc-fixed')[/code] 로 대체하긴 했다.
그리고 #2 스킨 기준으로 [code].area_view[/code] 인데, 스킨에 따라서 class 이름이 다르기 때문에 이 부분은 각자 바꿔주어야 한다. ([code]article_view[/code], [code]entry-content[/code] 등 존재)
CSS
이제 CSS를 추가해줘야 한다.
.toc-absolute {
position: absolute;
margin-top:165px;
}
.toc-fixed {
position: fixed;
top: 165px;
}
.toc {
left: 83%;
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-absolute와 toc-fixed를 이용해서 위치를 잘 이동시켜주면 된다. 앞서 html의 head 부분에 json과 css 파일을 추가해주었기 때문에 tocbot에서 제공하는 기본 색상과 효과로 작동한다. 따라서 색상이나 hover 등 더 다양하게 변경하고 싶다면 [3]을 참고해서 수정해주면 된다.
추가로, 꼭 스크롤을 해야 하위 목차가 보이는 현상이나 모바일 버전이나 태블릿 등에서 목차가 보이지 않게 하고 싶을 때는 [2]를 참고해서 수정해주면 된다.
[1] https://github.com/tscanlin/tocbot
GitHub - tscanlin/tocbot: Build a table of contents from headings in an HTML document.
Build a table of contents from headings in an HTML document. - GitHub - tscanlin/tocbot: Build a table of contents from headings in an HTML document.
github.com
티스토리 블로그 자동 목차(TOC)를 만들어보자.
1. 사용 할 라이브러리 https://tscanlin.github.io/tocbot/ Tocbot Tocbot builds a table of contents (TOC) from headings in an HTML document. This is useful for documentation websites or long markdown pages because it makes them easier to navigate. Th
ffxivblog.tistory.com
티스토리 Letter스킨 자동 목차 생성하기
벨로그와 다른 블로그를 사용했을 때, 편리했던 기능 중 하나인 자동 목차 기능을 티스토리에 적용해보자. 나는 티스토리의 Letter 스킨을 사용하고 있다. Tocbot이라는 라이브러리 사용하여 자동
agilejung.tistory.com