--- title: 使用CSS计数器 slug: Web/CSS/CSS_Counter_Styles/Using_CSS_counters tags: - CSS - CSS List - Web - counter - 教程 translation_of: Web/CSS/CSS_Lists_and_Counters/Using_CSS_counters original_slug: Web/CSS/CSS_Lists_and_Counters/Using_CSS_counters ---
本质上CSS计数器是由CSS维护的变量,这些变量可能根据CSS规则增加以跟踪使用次数。这允许你根据文档位置来调整内容表现。 CSS计数器是CSS2.1中自动计数编号部分的实现。
计数器的值通过使用{{cssxref("counter-reset")}} 和 {{cssxref("counter-increment")}} 操作,在 content 上应用 counter() 或 counters()函数来显示在页面上。
使用CSS计数器之前,必须重置一个值,默认是0。使用{{cssxref("counter()")}}函数来给元素增加计数器。 下面的CSS给每个h3元素的前面增加了 "Section <计算器值>:"。
body {
counter-reset: section; /* 重置计数器成0 */
}
h3:before {
counter-increment: section; /* 增加计数器值 */
content: "Section " counter(section) ": "; /* 显示计数器 */
}
例如:
<h3>Introduction</h3> <h3>Body</h3> <h3>Conclusion</h3>
{{ EmbedLiveSample('使用计数器', 300,200) }}
CSS计数器对创建有序列表特别有用,因为在子元素中会自动创建一个CSS计数器的实例。使用 counters() 函数,在不同级别的嵌套计数器之间可以插入字符串。比如这个CSS例子:
ol {
counter-reset: section; /* 为每个ol元素创建新的计数器实例 */
list-style-type: none;
}
li:before {
counter-increment: section; /* 只增加计数器的当前实例 */
content: counters(section, ".") " "; /* 为所有计数器实例增加以“.”分隔的值 */
}
结合下面的HTML:
<ol>
<li>item</li> <!-- 1 -->
<li>item <!-- 2 -->
<ol>
<li>item</li> <!-- 2.1 -->
<li>item</li> <!-- 2.2 -->
<li>item <!-- 2.3 -->
<ol>
<li>item</li> <!-- 2.3.1 -->
<li>item</li> <!-- 2.3.2 -->
</ol>
<ol>
<li>item</li> <!-- 2.3.1 -->
<li>item</li> <!-- 2.3.2 -->
<li>item</li> <!-- 2.3.3 -->
</ol>
</li>
<li>item</li> <!-- 2.4 -->
</ol>
</li>
<li>item</li> <!-- 3 -->
<li>item</li> <!-- 4 -->
</ol>
<ol>
<li>item</li> <!-- 1 -->
<li>item</li> <!-- 2 -->
</ol>
结果为:
{{ EmbedLiveSample('计数器嵌套') }}
| 规范 | 状态 | 注释 |
|---|---|---|
| {{SpecName("CSS3 Lists", "#auto-numbering", "CSS Counters")}} | {{Spec2("CSS3 Lists")}} | 无变化 |
| {{SpecName('CSS2.1', 'generate.html#generate.html#counters', 'counter-reset')}} | {{Spec2('CSS2.1')}} | 初始定义 |
另一个可用的示例在 http://www.mezzoblue.com/archives/20.../counter_intu/。这篇博客 发布于2006年11月1日,但是看上去写得还是准确的。