css 计数器就是采用 css 给一些 html 元素自动生成编号,比如类似 1.3.2 ,代码如下:
<style type="text/css"> | |
#demo1 ol { counter-reset: section; list-style-type: none; } | |
#demo1 ol li { counter-increment: section; } | |
#demo1 ol li:before { content: counters(section, ".") ". "; } | |
</style> | |
<div id="demo1"> | |
<ol> | |
<li>进风口的爽肤水 | |
<ol> | |
<li>非进口商的</li> | |
<li>非进口商的</li> | |
<li>非进口商的</li> | |
</ol> | |
</li> | |
<li>进风口的爽肤水 | |
<ol> | |
<li>非进口商的</li> | |
<li> | |
非进口商的 | |
<ol> | |
<li>将咖啡色的开发商</li> | |
<li>将咖啡色的开发商</li> | |
<li>将咖啡色的开发商</li> | |
<li>将咖啡色的开发商</li> | |
</ol> | |
</li> | |
<li>非进口商的</li> | |
</ol> | |
</li> | |
<li>进风口的爽肤水</li> | |
</ol> | |
</div> |
# 兼容性
IE8+,Chrome 和 Firefox 支持良好。属于 CSS2 范畴。
# 解释
# 初始化计数器
首先,给我们的计数器取一个名字,这个名字可以随便取,比如这里叫 section ,然后使用 counter-reset 在你需要开始计数的地方重置计数器:
ol { counter-reset: section; } |
# 计数器自增
然后通过 counter-incremen t 指定计数器何时自增,比如这里是碰到 li 就自增,所以我们写在 li 上面:
ol li { counter-increment: section; } |
# 显示计数器
最后,就是如何显示计数器了。显示计数器有 2 种方式,counter 和 counters,先讲 counter。
# counter
counter 只是简单的从前至后计数,忽略嵌套,语法如下:
counter(计数器名称, 可选的显示风格) // 默认风格为 decimal |
其中第二个参数为可选,表示计数器显示的风格,例如,你可以使用 upper-roman 以罗马数字显示,默认为 decimal ,即数字形式,其可选值大部分和 css 的 list-style-style 的一致,除了如下几个不被支持(不同浏览器支持的程度不一样):
- circle
- square
- lower-alpha
- upper-mongolian
我们使用 counter 把它显示到 li 的 :before 上面,并指定以大写罗马数字显示:
ol li:before { content: counter(section, upper-roman) ". ";} |
# counters
下面再来看看 counters,counters 和 counter 的最大区别是它会嵌套,什么是嵌套,我的表达能力有限,但我想大部分看到这里应该都明白了,就是类似 1.3.8 这种,
语法如下:
counters(计数器名称, 嵌套时拼接字符串, 可选的显示风格) |
比如我们使用点号 . 分割,
ol li:before { content: counters(section, "."); } |
另外,你可以将 counters 或者 counter 与任意字符串用空格拼接:
ol li:before { content: "我是字符串1" counters(section, ".") "我是字符串2" "我是字符串3"; } |
甚至 counter 和 counters 混用:
ol li:before { content: counter(section) ". " counters(section, ".", lower-alpha) ". "; } |
# 一些高级用法
# 使用中文计数
部分浏览器可能不支持
#demo5 ol { counter-reset: section; } | |
#demo5 ol li { counter-increment: section; } | |
#demo5 ol li:before { content: counter(section, cjk-ideographic) "、"; } |
# 自定义计数器起始值
#demo6 ol { counter-reset: section 5; } | |
#demo6 ol li { counter-increment: section; } | |
#demo6 ol li:before { content: counter(section) ". "; } |
# 自定义每次递增的值
#demo7 ol { counter-reset: section 5; } | |
#demo7 ol li { counter-increment: section 2; } | |
#demo7 ol li:before { content: counter(section) ". "; } |
# 递减计数
#demo8 ol { counter-reset: section 6; } | |
#demo8 ol li { counter-increment: section -1; } | |
#demo8 ol li:before { content: counter(section) ". "; } |
# 多个计数器同时使用
#demo9 ol { counter-reset: section; } | |
#demo9 ol li { counter-increment: section; } | |
#demo9 ol li:before { content: "==" counter(section, lower-alpha) counters(sectio |