網頁設計中的計數器及其使用

計數器

我們都已經對計數器很熟悉了,例如,有序列表中的列表項標志就是計數器。在網頁建設中,沒有辦法影響這些計數器很大程度上是因為沒有這個必要:HTML為有序列表定義了自己的計數行為,這就足夠了。隨著XML的出現,現在需要提供一種定義計釋器的方法,這很重要。不過,CSS2沒有滿足于只是提供HTML中的簡單計數。它增加了兩個屬性和兩個content值,從而可以定義幾乎所有計數格式,包括采用多種樣式的小節(jié)計數器,如“VII.2.C”。

使用計數器

不過,要在網頁設計中具體顯示計數器,還需要結合使用content屬性和一個與計數器有關的值。要了解這是如何做到的,下面以一個基于XML的有序列表為例,如下:


<list type="ordered">

<item>First item</item>

<item>Xtem two</item>

<item>The third itera</item>

</list>

向采用此結構的XML應用以下規(guī)則,可以得到如圖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的元素。實際上,任何元素都可以利用計數器??紤]以下規(guī)則:


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.”。計數器由同一個元素遞增和使用時,遞增發(fā)生在計數器顯示之前。類似地,如果計數器在同一個元素中重置和顯示,重置也在計數器顯示之前發(fā)生??紤]以下規(guī)則:


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>

可以用以下規(guī)則改寫B(tài)ASIC程序清單的傳統(tǒng)格式:

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,

有意思的是,在網頁設計中,即使規(guī)則看上去會讓計數器遞增,但實際上display為none的元素并不會遞增計數器。相反,visibility為hidden的元素確實會遞增計數器:

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

/*'cntr' is NOT incremented */

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

/*'cntr' IS incremented */


網站建設、網絡營銷咨詢專線:0871-63535511(點擊可一鍵撥號)