【问题标题】:Creating table of contents in html在html中创建目录
【发布时间】:2012-12-17 18:59:54
【问题描述】:

是否可以创建如下所示的有序列表? 我喜欢这个用于我正在创建的目录。

  1. 进入
  2. 第 1 节
    2.1 小节1
    2.2 小节2
  3. 第 2 节
    .....

我有以下内容,但每个小节都从 1 开始。

<ol>
    <li>
        <a href="#Lnk"></a>
    </li>
    <li>
        <a href="#Lnk"></a>
    </li>
    <ol>
        <li>
            <a href="#Lnk"></a>
        </li>
        <li>
            <a href="#Lnk"></a>
        </li>
    </ol>
</ol>

谢谢

【问题讨论】:

    标签: html tableofcontents


    【解决方案1】:

    这确实可以用纯 CSS 完成:

    ol {
        counter-reset: item;
    }
    
    li {
        display: block;
    }
    
    li:before {
        content: counters(item, ".")" ";
        counter-increment: item;
    }
    

    fiddle 的示例相同。

    【讨论】:

    • 我无法让它工作。复制最后一个
        标记在顶层给出了一个数字 2.3,而不是预期的 3。
    • @pheon 那个小提琴有一个轻微的错字。 ol 只能有 li 孩子。任何嵌套的ol 都必须包含在li 中。更新:jsfiddle.net/jasonkarns/6xkzv37e
    【解决方案2】:

    有相当多的 jQuery 插件可以生成目录。

    【讨论】:

    【解决方案3】:

    你看过这篇文章吗: Number nested ordered lists in HTML

    我认为不使用 JS 是做不到的。

    【讨论】:

    【解决方案4】:

    这段代码会导致我想要的输出:

    <ol>
      <li>
        <a href="#Lnk">foo</a>
      </li>
      <li>
        <a href="#Lnk">bar</a>
        <ol>
          <li>
            <a href="#Lnk">baz</a>
          </li>
          <li>
            <a href="#Lnk">qux</a>
          </li>
        </ol>
      </li>
      <li>
        <a href="#Lnk">alpha</a>
        <ol>
          <li>
            <a href="#Lnk">beta</a>
          </li>
          <li>
            <a href="#Lnk">gamma</a>
          </li>
        </ol>
      </li>
    </ol>
    

    CSS:

    ol {
        counter-reset: item;
    }
    li {
        display: block;
    }
    li::before {
        content: counters(item, ".")". ";
        counter-increment: item;
    }
    

    小提琴:http://jsfiddle.net/Lepetere/evm8wyj5/1/

    【讨论】:

      【解决方案5】:

      就我自己而言,我对现有的解决方案并不满意。所以我用Python3BeautifulSoup创建了一个解决方案。

      该函数将 HTML 源代码作为字符串并查找标题标签(例如 h1)。在接下来的步骤中,会为标题和相应的目录条目创建一个 id=

      def generate_toc(html_out):
          """Create a table of content based on the header tags.
          
          The header tags are used to create and link the toc.
          The toc as place on top of the html output.
          
          Args:
              html_out(string): A string containing the html source.
      
          Returns:
              (string): The new string.
          """
          from bs4 import BeautifulSoup
      
          # the parser
          soup = BeautifulSoup(html_out, 'html.parser')
      
          # create and place the div element containing the toc
          toc_container = soup.new_tag('div', id='toc_container')
          first_body_child = soup.body.find_all(recursive=False)[0]
          first_body_child.insert_before(toc_container)
          # toc headline
          t = soup.new_tag('p', attrs={'class': 'toc_title'})
          t.string = 'Inhalt'
          toc_container.append(t)
      
          def _sub_create_anchor(h_tag):
              """Create a toc entry based on a header-tag.
              The result is a li-tag containing an a-tag.
              """
              # Create anchor
              anchor = uuid.uuid4()
              h_tag.attrs['id'] = anchor  # anchor to headline
              # toc entry for that anchor
              a = soup.new_tag('a', href=f'#{anchor}')      
              a.string = h_tag.string
              # add to toc
              li = soup.new_tag('li')
              li.append(a)
              return li
      
          # main ul-tag for the first level of the toc
          ul_tag = soup.new_tag('ul', attrs={'class': 'toc_list'})
          toc_container.append(ul_tag)
      
          # helper variables
          curr_level = 1
          ul_parents = [ul_tag]
      
          # header tags to look for
          h_tags_to_find = [f'h{i}' for i in range(1, 7)]  # 'h1' - 'h6'
          for header in soup.find_all(h_tags_to_find):
              next_level = int(header.name[1:])
      
              if curr_level < next_level:  # going downstairs
                  # create sub ul-tag
                  sub_ul_tag = soup.new_tag('ul', attrs={'class': 'toc_list'})
                  # connect it with parent ul-tag
                  ul_parents[-1].append(sub_ul_tag)
                  # remember the sub-ul-tag
                  ul_parents.append(sub_ul_tag)
              elif curr_level > next_level:  # going upstairs
                  # go back to parent ul-tag
                  ul_parents = ul_parents[:-1]
      
              curr_level = next_level
      
              # toc-entry as li-a-tag
              li_tag = _sub_create_anchor(header)
              # add to last ul-tag
              ul_parents[-1].append(li_tag)
      
          return soup.prettify(formatter='html5')
      

      这在您的所有用例中可能并不优雅。我自己将 TOC 放在数据科学例程(例如 pandas)生成的 HTML 报告之上。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-04-20
        • 1970-01-01
        • 2017-11-24
        • 1970-01-01
        • 2019-05-28
        • 1970-01-01
        • 2010-10-20
        相关资源
        最近更新 更多