为 Hugo 添加一个目录

在 Hugo 中添加一个美观易用的目录

创建 JavaScript 文件

在 Hugo 主题文件夹中,找到路径 static/js 新建文件 toc.js

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
function debounce(func, wait, options = {
    immediate: false,
    middle: true,
    thisArg: null,
  }) {
    let timer;
    let restDate = new Date();
    const immediate = options.immediate !== false;
    const middle = options.middle !== false;
    const thisArg = options.thisArg || null;
    return function (...args) {
      timer && clearTimeout(timer);
      let isFirst = !timer;
      timer = setTimeout(() => {
        func.apply(thisArg, args);
        restDate = new Date();
      }, wait);
      if ((new Date() - restDate > wait && middle) || (isFirst && immediate)) {
        clearTimeout(timer);
        func.apply(thisArg, args);
        restDate = new Date();
      }
    }
  }
  
  function setActive(anchors) {
    const ele = anchors.find((ele, index, arr) => {
      return ele.getBoundingClientRect().top >= 0 || index >= arr.length - 1;
    });
    if (ele) {
      const tableOfContents = document.querySelector('#table-of-contents');
      const toActive = tableOfContents.querySelector(`a[href="#${ele.id}"]`);
      if (!toActive) return;
      const activeA = tableOfContents.querySelector(`.active`);
      if (activeA) activeA.classList.remove('active');
      toActive.classList.add('active');
      window.history.pushState(null, null, `#${ele.id}`);
      tableOfContents.scrollTo({
        left: 0,
        top: toActive.offsetTop - tableOfContents.getBoundingClientRect().height / 2,
        behavior: 'smooth',
      });
    }
  }
  
  function initContents(icon = '<svg t="1690868184633" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3381" width="32" height="32"><path d="M128 192l768 0 0 128-768 0 0-128Z" fill="#666666" p-id="3382"></path><path d="M128 448l768 0 0 128-768 0 0-128Z" fill="#666666" p-id="3383"></path><path d="M128 704l768 0 0 128-768 0 0-128Z" fill="#666666" p-id="3384"></path></svg>') {
    if(document.querySelector('#table-of-contents-wapper')) return;
    const contents = document.createElement('details');
    contents.id = 'table-of-contents-wapper';
    contents.innerHTML = `<summary>
      ${icon}
    </summary>`
    const styleElement = document.createElement('style')
    styleElement.innerHTML = `
    #table-of-contents-wapper {
      user-select: none;
      position: fixed;
      right: 1em;
      top: 4em;
      border-radius: 8px;
      z-index: 999
    }
  
    @media only screen and (min-width:768px) {
      #table-of-contents-wapper[open] summary {
        position: relative;
        left: 5.8em
      }
    }
  
    @media only screen and (max-width:768px) {
      #table-of-contents-wapper {
        top: auto;
        right: auto;
        bottom: 1.8rem;
        left: 1.8rem
      }
    }
  
    #table-of-contents-wapper summary {
      display: inline-block;
      font-size: 1.5em;
      border-radius: 4px;
      cursor: pointer;
      padding: .2em
    }
  
    #table-of-contents-wapper #table-of-contents {
      line-height: 1.3;
      width: 19rem;
      font-size: 15px;
      padding: .8em;
      border: 1px solid;
      border-radius: 6px;
      overflow-y: scroll;
      max-height: calc(100vh - 20rem);
      background-color: rgba(150, 150, 150, 0.8);
      color: #ffffff
    }
  
    #table-of-contents-wapper #table-of-contents a {
      width: 60%;
      display: inline-block;
      color: currentColor;
      line-height: 1.3;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis
    }
  
    #table-of-contents-wapper #table-of-contents .active {
      border-left: 2px solid #bedfff;
      color: #bedfff
    }
  
    .content h1,
    .content h2,
    .content h3 {
      padding-top: 2em !important;
      margin-top: -2em !important
    }`;
  
    const anchors = [...document.querySelector('.content').querySelectorAll('h1[id],h2[id],h3[id],h4[id]')];
    if (!anchors.length) return contents.remove();
    const tableOfContents = document.createElement('div');
    tableOfContents.id = 'table-of-contents';
    anchors.forEach(ele => {
      const a = document.createElement('a');
      if (!ele.innerText) return;
      a.innerText = ele.innerText;
      a.href = `#${ele.id}`;
      a.style.paddingLeft = `${ele.tagName.charAt(1)}em`;
      tableOfContents.appendChild(a);
    });
  
    contents.appendChild(tableOfContents);
    contents.open = window.innerWidth >= 768;
  
    document.head.appendChild(styleElement);
    document.body.append(contents);
  
    setActive(anchors);
    const debounceSetActive = debounce(setActive, 200)
    window.addEventListener('scroll', () => {
      debounceSetActive(anchors);
    });
  }

创建 toc.html 文件

此文件用于在页面中导入第一步中的 JavaScript

在主题文件夹下的 layouts\partials\post 目录中,新建 toc.html

1
2
3
4
{{ if .Params.toc }}
<script src="/js/toc.js"></script>
<script>initContents()</script>
{{ end }}

新建完成后在主题文件夹下的 layouts\posts 目录中,找到 <footer></footer> 标签,插入下面代码

1
{{ partial "posts/toc.html" . }}

此时,在 Markdown 文件上方添加 toc = true 即可显示目录,效果请访问此页

(可选)修改 Markdown 文件模板

找到 archetypes 目录,修改 default.md 文件

+++ 之间添加下面行

1
toc = false

这样在使用 hugo new 命令时,创建的文件会自动包含 toc 项,按需设置为 true 即可