代码之家  ›  专栏  ›  技术社区  ›  Technical Bard

HTML/CSS自动编号标题?

  •  18
  • Technical Bard  · 技术社区  · 16 年前

    有没有一种方法(理想情况下很容易)使HTML/CSS中的标题和章节自动编号?也许是JS库?

    或者这在HTML中很难做到吗?

    7 回复  |  直到 16 年前
        1
  •  4
  •   Community Mohan Dere    8 年前

    当然可以使用css计数器——只要确保你注意浏览器的兼容性。..:

    <style>
       body{counter-reset: section}
       h2{counter-reset: sub-section}
       h3{counter-reset: composite}
       h4{counter-reset: detail}
    
       h2:before{
         counter-increment: section;
         content: counter(section) " ";
       }
       h3:before{
         counter-increment: sub-section;
         content: counter(section) "." counter(sub-section) " ";
       }
       h4:before{
         counter-increment: composite;
         content: counter(section) "." counter(sub-section) "." counter(composite) " ";
       }
       h5:before{
         counter-increment: detail;
         content: counter(section) "." counter(sub-section) "." counter(composite) "." counter(detail) " ";
       }
       </style>
    

    it's the same as another question

    还要注意,使用css将 更改标题(例如,所选文本将为您提供不带数字的标题)。这可能是可取的,也可能不是可取的。lpfavreau(已接受)的答案将为您提供修改标题文本的jquery代码。

    MDN: Using CSS counters 了解详情。

    第三方编辑

    example with the css above

        2
  •  34
  •   Community Mohan Dere    8 年前

    2016年更新。请看 Stephen's answer 下面是CSS中正确的方法。我的答案在2009年是有道理的,当时浏览器和库是不同的。我们现在生活在一个全新的世界,这里提出的方法已经过时了。我把它留给那些仍然生活在由IE7和眼泪组成的企业微观世界中的可怜灵魂。


    this other question 如果你想知道如何在CSS中做到这一点,答案可能就是你想要的。但是titel也有一个很好的建议,这取决于你的HTML文档是如何制作的。

    应该指出的是,正如Triptych在另一条评论中所说,只有当它是一个内部工具,你可以控制使用哪些浏览器,并且使用CSS是值得的,因为修改HTML会很困难。此CSS功能的支持是有限的。

    当然,使用类似的东西很容易 jQuery 也要做增量。类似于以下未经测试的片段:

    $(document).ready(function() {
      $('h1').each(function(index) {
        $(this).html((index + 1) + '. ' + $(this).html());
      });
    });
    

    当然,不要忘记在文档中包含jquery.js文件。

        3
  •  3
  •   Luis Melgratti    15 年前

    最简单的方法是编号列表

    <ol>
    <li> Section
        <ol>
          <li>Nested one</li>
          <li>Nested two</li>
        </ol>
    </li>
    <li>Section</li>
    <li>Section</li>
    <li>Section</li>
    <ol>
    

    将类似于:




    1. 部分
        4
  •  0
  •   Arve Systad    16 年前

    可以在服务器端或使用JavaScript完成。不过,我不知道有什么预制脚本可以做到这一点。

        5
  •  0
  •   sebnow    16 年前

    列表可以,为什么其他元素不行? http://www.w3.org/TR/CSS2/generate.html#scope

        6
  •  0
  •   Satish    16 年前
    <ol>
      <li>Heading 1</li>
      <li>Heading 2</li>
      <li>Heading 3</li>
    </ol>