网页设计中的计数器及其使用

  • 2019-05-30 17:04:03
  • 阅读次数:
  • 作者:盈岚科技小编
  • 来源:http://www.lyjtt.cn

计数器

我们都已经对计数器很熟悉了,例如,有序列表中的列表项标志就是计数器。在网页建设中,没有办法影响这些计数器很大程度上是因为没有这个必要:HTML为有序列表定义了自己的计数行为,这就足够了。随着XML的出现,现在需要提供一种定义计释器的方法,这很重要。不过,CSS2没有满足于只是提供HTML中的简单计数。它增加了两个属性和两个content值,从而可以定义几乎所有计数格式,包括采用多种样式的小节计数器,如“VII.2.C”。

使用计数器

不过,要在网页设计中具体显示计数器,还需要结合使用content属性和一个与计数器有关的值。要了解这是如何做到的,下面以一个基于XML的有序列表为例,如下:


<list type="ordered">

<item>First item</item>

<item>Xtem two</item>

<item>The third itera</item>

</list>

向采用此结构的XML应用以下规则,可以得到如图12-22所示的结果:


list[type="ordered"]{counter-reset: ordered;}/* defaults to 0 */

list[type="ordered"] item {display: block;}

list[type="ordeired"] item:before {counter-increment: ordered; content: counter(ordered)";margin: 0.25em 0;}

注意,与平常一样,生成内容作为行内内容放在相关元素的开始位置。因此,其效果类似于声明了list-style-position: inside;的HTML列表。


还要注意,item元素是生成块级框的普通元素,这说明计数器并不仅限于display为 list-itexn的元素。实际上,任何元素都可以利用计数器。考虑以下规则:


h1:before (counter-reset: section subsec;

counter-increment: chapter;

content: counter(chapter)".";}

h2:before {counter-reset: subsec;

counter-increment: section;

content: counter(chapter )"." counter(section)}.

h3:before {counter-increment: subsec;

content: counter(chapter)"." counter(section)"." counter(subsec)".";}

注意h1元素如何使用计数器chapter,该计数器默认为0,但在元素文本前却显示了一个“1.”。计数器由同一个元素递增和使用时,递增发生在计数器显示之前。类似地,如果计数器在同一个元素中重置和显示,重置也在计数器显示之前发生。考虑以下规则:


h1:before, h2:before, h3:before {

content: counter(chapter)"." counter(section)"." counter(subsec)".";}

h1 {counter-reset: section subsec;

counter-increment: chapter;}

文档中第一个h1元素前面有文本"1.0.0.”,因为计数器section和subsec都重置,但没有递增。这意味着如果希望一个递增计数器第一次显示0,只需将该计数器重置为-1,如下:

body {counter-reset: chapter -1;}

h1:before {counter-increment: chapter; content: counter(chapter)".";}

对计数器还可以做一些有意思的事情。考虑以下XML:

<code type="BASIC">

<line>PRINT "Hello world!"</line>

<line>REM This is what Che kids are calling a "comment"</line>

<line>G0T0 10</line>

</code>

可以用以下规则改写BASIC程序清单的传统格式:

code[type="BASIC"]{counter-reset: linenum;

font-family: monospace;}

code[type="BASIC"] line {display: block;}

code[type:"BASIC"] line:before {counter-increment: Xinenum; content: counter(linenum 10)":";}

还可以为每个计数器定义一个列表样式,作为counter ()格式的一部分。为此可以在计数器的标识符后面增加一个list-style-type关键字,用逗号分隔。

注意,没有为计数器section指定样式关键字,所以它默认为decimal计数样式。如果愿意,甚至可以将计数器设置为使用样式disc、circle、square和none,

有意思的是,在网页设计中,即使规则看上去会让计数器递增,但实际上display为none的元素并不会递增计数器。相反,visibility为hidden的元素确实会递增计数器:

.suppress {counter-increment: entr; display: none;}

/*'cntr' is NOT incremented */

.invisible {counter-increment: cntr; visibility: hidden;}

/*'cntr' IS incremented */


当前文章标题:网页设计中的计数器及其使用

当前URL:http://www.lyjtt.cn/news/wzzz/3035.html

上一篇:网页设计中的生成引号

下一篇:网页设计中的重置和递增

网站建设、网络营销咨询专线:181-8386-5875(点击可一键拨号)