Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

javascript - HTML / CSS autonumber headings?

Is there a way (ideally easy) to make headings and sections autonumber in HTML/CSS? Perhaps a JS library?

Or is this something that is hard to do in HTML?

I'm looking at an application for a corporate wiki but we want to be able to use heading numbers like we always have in word processors.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Definitely possible using css counters - just make sure you watch out for browser compatibility...:

This will make h2 get 1., 2., h3 gets 1.1, 2.1, 2.2 etc...

<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>

As lpfavreau says, it's the same as another question I believe.

Also note that using css will not change the heading (e.g. selected text will give you the heading without the numbers). This may or may not be desirable. lpfavreau's (accepted) answer will give you the jquery code to modify the heading text.

See MDN: Using CSS counters for details.

3rd Party Edit

I created an example with the css above


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...