Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

คุณสมบัติ counterIncrement ของ HTML DOM Style: เพิ่มค่าตัวนับ CSS

คุณสมบัติ counterIncrement ใช้สำหรับเพิ่มหรือลดค่าของ CSS Counter หนึ่งหรือหลายตัว ใช้ร่วมกับ counterReset และ content

ไวยากรณ์ (Syntax)

object.style.counterIncrement = "none|name number|initial|inherit"

ค่าที่รองรับ

ค่าคำอธิบาย
noneไม่เพิ่ม counter ใดๆ (ค่าเริ่มต้น)
name numberชื่อ counter และจำนวนที่เพิ่ม (ค่าเริ่มต้น number = 1, รองรับ 0 และค่าลบ)
initialตั้งค่ากลับเป็นค่าเริ่มต้น
inheritสืบทอดจากพาเรนต์

ตัวอย่างการใช้งาน

<!DOCTYPE html>
<html>
<head>
<style>
  ul {
    counter-reset: demo_var;
  }
  li::after {
    counter-increment: demo_var 10;
    content: " " counter(demo_var) ".";
  }
</style>
<script>
  function incrementCounterVal() {
    document.getElementsByTagName("li")[0].style.counterIncrement = "demo_var 2";
    document.getElementById("Sample").innerHTML = "ค่า counter increment เพิ่มขึ้น 2 แล้ว";
  }
</script>
</head>
<body>
<ul>
  <li>Demo =</li>
  <li>Demo =</li>
  <li>Demo =</li>
  <li>Demo =</li>
  <li>Demo =</li>
</ul>
<p>คลิกปุ่มเพื่อเพิ่มค่า counter increment ของรายการด้านบน</p>
<button onclick="incrementCounterVal()">เพิ่มค่า Counter</button>
<p id="Sample"></p>
</body>
</html>

ผลลัพธ์

ก่อน: ทุก li เพิ่ม 10 (10, 20, 30, 40, 50)
หลังคลิก: li แรกเพิ่มแค่ 2 (2, 12, 22, 32, 42) - เพราะเปลี่ยนเฉพาะ li แรก

การใช้งานขั้นสูง

/* เพิ่มหลาย counter พร้อมกัน */
.item {
  counter-increment: items 1 sections 1;
}

/* ลดค่า (Negative increment) */
.step-back {
  counter-increment: step -1;
}

/* ไม่เพิ่ม counter บางรายการ */
li.skip::before {
  counter-increment: none;
  content: "⏭ ";
}

/* Reverse numbering */
ol.reversed {
  counter-reset: list 11;           /* เริ่มที่ 11 */
}
ol.reversed li::before {
  counter-increment: list -1;       /* ลดลง 1 ทีละรายการ */
  content: counter(list) ". ";
}

ฟังก์ชัน counter() และ counters()

ฟังก์ชันการใช้งานตัวอย่างผลลัพธ์
counter(name)แสดงค่า counter เดียว"1", "2", "3"
counter(name, style)แสดงพร้อมรูปแบบ"i", "ii", "iii" (lower-roman)
counters(name, string)แสดง nested counters"1.1", "1.2", "2.1"
counters(name, string, style)nested + รูปแบบ"i.a", "i.b", "ii.a"

รูปแบบการนับ (Counter Styles)

counter(section, decimal)        /* 1, 2, 3 */
counter(section, lower-roman)    /* i, ii, iii */
counter(section, upper-roman)    /* I, II, III */
counter(section, lower-alpha)    /* a, b, c */
counter(section, upper-alpha)    /* A, B, C */
counter(section, thai)           /* ๑, ๒, ๓ */
counter(section, cjk-decimal)    /* 一, 二, 三 */

คุณสมบัติที่เกี่ยวข้อง

  • counterReset - สร้าง/รีเซ็ต counter
  • content - แสดงค่า (ใน pseudo-elements)

การรองรับเบราว์เซอร์

รองรับทุกเบราว์เซอร์สมัยใหม่ (IE8+)