Notice
Recent Posts
Recent Comments
05-04 20:03
Archives
관리 메뉴

develop myself

tistory 블로그 toc 적용(반응형 #2 스킨) 본문

Tips/blog

tistory 블로그 toc 적용(반응형 #2 스킨)

insightous 2023. 1. 10. 12:24

1 반응형 #2 스킨

2 TOC

TOC : Table Of Contents

제목으로 설정한 텍스트에 목차를 자동으로 생성해 준다.

적용 방법: HTML, CSS 추가

3 TOC 적용 방법

3.1 html > head 추가

블로그 관리 > 꾸미기:스킨 편집 > html 편집 > HTML

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

/head를 검색하여 그 위에 추가하면 좋다.

head에 위 코드를 추가한 결과 이미지

3.2 html > body 추가

블로그 관리 > 꾸미기:스킨 편집 > html 편집 > HTML

3.2.1 본문에 toc가 들어갈 부분 추가

s_article_rep > s_permalink_article_rep 태그 아래 추가한다.

s_permalink_article_rep 태그는 여러 개 있을 수 있기 때문에, s_article_rep 아래의 s_permalink_article_rep 에 아래 코드를 추가한다.

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

코드를 추가한 결과 이미지

3.2.2 스크립트 추가

<!-- TOC -->
<script>
    var content = document.querySelector('.area_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: '.area_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>

/body를 검색하여 그 위에 추가하면 좋다.

코드를 추가한 결과 이미지

3.3 CSS 추가

블로그 관리 > 꾸미기:스킨 편집 > html 편집 > CSS

/* TOC */
.toc-absolute {
  position: absolute;
  margin-top: 24px;
}
.toc-fixed {
  position: fixed;
  top: 165px;
}

.toc {
  right: calc((100% - 1430px) / 2 - 250px);
  width: 250px;
  padding: 10px;
  box-sizing: border-box;
}

.toc-list {
  margin-top: 14px !important;
  font-size: 1.0em;
}

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

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

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

- API : tscanlin.github.io/tocbot/

- 코드 참고: https://leeari95.tistory.com/4

- CSS 수정 참고: https://depast.tistory.com/40#3-%ED%8F%AC%EC%8A%A4%ED%8C%85-%ED%95%B4%EB%B3%B4%EA%B8%B0

Comments