
4.4 动态伪类选择器
伪类选择器并不是针对真正的元素使用的选择器,只针对CSS中的伪元素起作用。
4.4.1 内容相关的属性

内容相关的属性与CSS其他属性一样,同样需要定义在CSS样式的大括号内。content属性是CSS支持的内容相关属性中最重要的一个,该属性的值可以是字符串、url、attr、open-quote等格式,该属性用于向指定元素之前或之后插入指定内容。
【例4-7】(实例文件:ch04\Chap4.7.html)内容相关的属性。

在上面的代码中,为每一个li之前添加字符串,并设置了字体颜色为红色。
相关的代码实例请参考Chap4.7.html文件,在IE浏览器中运行的结果如图4-10所示。

图4-10 内容相关的属性
4.4.2 插入图像

content属性值除了可以添加字符串外,还可以添加图片,代码如下。
content: url("src")
src指定图片的路径。
【例4-8】(实例文件:ch04\Chap4.8.html)插入图片。

相关的代码实例请参考Chap4.8.html文件,在IE浏览器中运行的结果如图4-11所示。

图4-11 插入图像
4.4.3 只插入部分元素

有时候只想为一部分元素添加内容,这时需先把要添加内容的元素找到,如只想给前两个元素添加内容,只需找到前两个元素的选择器,再在其后面添加伪类选择器,这样就可以设置其内容了。
【例4-9】(实例文件:ch04\Chap4.9.html)只插入部分元素。

相关的代码实例请参考Chap4.10.html文件,IE浏览器中运行的结果如图4-12所示。

图4-12 只插入部分元素
4.4.4 配合quotes属性执行插入

quotes属性可以定义open-quote和close-quote,然后就可以在content属性中应用它们了。
【例4-10】(实例文件:ch04\Chap4.10.html)配合quotes属性执行插入。

相关的代码实例请参考Chap4.10.html文件,在IE浏览器中运行的结果如图4-13所示。

图4-13 配合quotes属性执行插入
4.4.5 配合counter-increment属性添加编号

counter-increment属性用于定义计数器,如要给多条内容添加编号,就可以通过该属性来设置。定义计数器很简单,只需给需要添加编号的元素定义一个计数器,然后结合content属性在该元素前面添加这个计数器,就可以实现编号了。
【例4-11】(实例文件:ch04\Chap4.11.html)配合unter-increment属性添加编号。

相关的代码实例请参考Chap4.11.html文件,在IE浏览器中运行的结果如图4-14所示。

图4-14 计数器添加编号效果
4.4.6 使用自定义编号

从上面的案例可以发现,CSS默认的编号样式是数字,但有时我们还需要使用自定义编号来满足不同的需要。我们可以通过counter(name,list-style-type)用法来实现使用自定义编号,name是计数器的名字,list-style-type指定自定义编号的样式,它的一部分取值如表4-1所示。
表4-1 自定义编号部分取值

【例4-12】(实例文件:ch04\Chap4.12.html)使用自定义编号。

相关的代码实例请参考Chap4.12.html文件,在IE浏览器中运行的结果如图4-15所示。

图4-15 使用自定义编号
4.4.7 添加多级编号

在上面案例中,只是添加了一级编号,还可以添加多级编号,像书的目录一样,可以有多级的编号。下面就使用计数器来实现一个简单的目录形式的编号。
【例4-13】(实例文件:ch04\Chap4.13.html)添加多级编号。

相关的代码实例请参考Chap4.13.html文件,在IE浏览器中运行的结果如图4-16所示。
我们会发现第二级编号是连续的,正常情况下每一章的第一节应该从1开始,上面的效果不是我们想要的,但是我们可以通过counter-reset属相来改变,该属性用于重置计数器。我们在h2样式中添加“counter-reset:order2;”即可,这样就会重置order2计数器,显示效果如图4-17所示。

图4-16 多级计数器的应用

图4-17 重置order2计数器后的效果