Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách tăng giá trị bộ đếm (counter) với JavaScript

Sử dụng thuộc tính counterIncrement để tăng giá trị của một hoặc nhiều bộ đếm CSS. Điều này thường dùng kết hợp với ::before hoặc ::after và hàm counter() để tự động đánh số.

Ví dụ minh họa

Nhấn nút để thay đổi bộ đếm của mục "Java" từ "section" sang "subsection":

<!DOCTYPE html>
<html>
<head>
  <style>
    h2 {
      counter-increment: section;
    }
    h2:before {
      content: counter(section) " Quiz ";
    }
  </style>
</head>
<body>
  <h1>Các bài Quiz</h1>
  <p>Thay đổi counterIncrement</p>
  <h2>Ruby</h2>
  <h2 id="myID">Java</h2>
  <h2>PHP</h2>
  <h2>Perl</h2>
  <button onclick="display()">Cập nhật Counter Increment</button>
  <script>
    function display() {
      document.getElementById("myID").style.counterIncrement = "subsection";
    }
  </script>
</body>
</html>

Cú pháp counterIncrement

counterIncrement: none | name number | initial | inherit

  • name: Tên bộ đếm (ví dụ: section, subsection)
  • number: Giá trị tăng (mặc định là 1, có thể âm)
  • Có thể liệt kê nhiều bộ đếm: counterIncrement: section 2 subsection 1