如下面這種需要累計序號的,因為某些行不一定存在,通常是用js去定義一個變量來記錄這個序號。但還有一種純css實現(xiàn)計數(shù)的方法。
改了下菜鳥教程的例子,可以更好理解這個計數(shù)器,代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鳥教程(runoob.com)</title>
<style>
.box1 {
counter-reset: xxxx; /* 重置計數(shù)器成0 */
}
.box1 h3:before {
counter-increment: xxxx; /* 增加計數(shù)器值 */
content: "計數(shù)器" counter(xxxx) ": "; /* 顯示計數(shù)器 */
}
.box2 {
counter-reset: dddd; /* 重置計數(shù)器成0 */
}
.box2 h3:before {
counter-increment: dddd; /* 增加計數(shù)器值 */
content: "測試" counter(dddd) ": "; /* 顯示計數(shù)器 */
}
/* 注意:這里使用demo2的計數(shù)器,可以看到是累計的!!! */
.demo:before{
counter-increment: dddd; /* 增加計數(shù)器值 */
content: "測試" counter(dddd) ": "; /* 顯示計數(shù)器 */
}
</style>
</head>
<body>
<div class="box1">
<h1>使用 CSS 計數(shù)器demo1:</h1>
<h3>GOOGLE</h3>
<h3>RUNOOB</h3>
<h3>TAOBAO</h3>
</div>
<div class="box2">
<h1>使用 CSS 計數(shù)器demo2:</h1>
<h3>GOOGLE</h3>
<h3>RUNOOB</h3>
<h3>TAOBAO</h3>
</div>
<div class="box1">
<h1>使用 CSS 計數(shù)器demo3:</h1>
<h3>GOOGLE</h3>
<h3>RUNOOB</h3>
<h3>TAOBAO</h3>
</div>
<div class="demo">使用 CSS 計數(shù)器demo4:</div>
</body>
</html>
屬性介紹
counter-reset
用于將 CSS 計數(shù)器重置為制定值
比如上面的demo1和demo3使用的同一個計數(shù)器 “xxxx” ,這個可以隨便定義,在需要計數(shù)的地方使用counter-increment設(shè)置為這個值即可。
counter-increment
counter-increment屬性用于將CSS Counters (en-US)的值增加給定值
counter()函數(shù)
真正統(tǒng)計的函數(shù),統(tǒng)計你指定的這個計數(shù)器出現(xiàn)了多少次。
直白理解
就是counter-reset 設(shè)置個值,用于代表同一類計數(shù)器,然后需要累計的元素上搭配counter-increment、counter。counter-increment用于+1操作,counter計算這類計數(shù)器出現(xiàn)了多少次。后面如果再遇到counter-reset,則重置counter-reset后面設(shè)置的這個計數(shù)器,標記increment后也從1開始累加。
注意:counter-reset不是說只會限制在當(dāng)前這個父元素內(nèi)部!仔細看上面的demo4就理解了!計數(shù)器其實是個全局的變量!建議每次使用時都先使用counter-reset重置下,每次都重新計數(shù)。
若對你有幫助,請點個贊吧,若能打賞不勝感激,謝謝支持!
本文地址:http://www.lxweimin.com/p/8c8b81007f0d?v=1695716521065,轉(zhuǎn)載請注明出處,謝謝。
參考:
https://www.runoob.com/cssref/func-counter.html
https://developer.mozilla.org/zh-CN/docs/Web/CSS/counter-reset
https://developer.mozilla.org/zh-CN/docs/Web/CSS/counter-increment