You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让HTML有序列表序号突破两位限制,实现连续编号?

有序列表搜索后序号异常(00-99循环、无法显示三位数字)解决方案

问题背景

现有一套实现列表搜索功能的代码,搜索逻辑运行正常,但在<ol>有序列表中使用时,序号从“00”开始计数,到99后会重复回到00,无法正确显示100及以上的三位数字序号。

现有代码

JavaScript

function search_animal() {
  let input = document.getElementById('searchbar').value
  input = input.toLowerCase();
  let links = document.querySelectorAll('#list li');

  links.forEach((e) => {
    e.classList.toggle("active", e.innerText.toLowerCase().includes(input))
  });
}

let searchbar = document.querySelector("#searchbar");
searchbar.addEventListener("input", search_animal);

HTML

<input id='searchbar'>
<ol id='list'>
  <div class="animals">
    <li><a target="_blank" href="example.com">Example</a></li>
    <li><a target="_blank" href="example.com">Example</a></li>
    <li><a target="_blank" href="example.com">Example</a></li>
    <!-- 列表项重复至超过100个 -->
  </div>
</ol>

问题根源

这个序号异常和JS搜索逻辑无关,核心原因是你大概率使用了CSS自定义计数器来格式化序号,且采用了decimal-leading-zero格式——这个格式只会生成最多两位的前置零序号(00-99),当列表项超过99个时,计数器会循环重置。

解决方案

方案1:自定义支持任意位数的计数器样式

如果需要保留前置零的序号样式,通过@counter-style定义自定义计数器,指定需要的前置零位数:

/* 定义自定义计数器,设置3位前置零(可根据需求修改数字) */
@counter-style custom-leading-zero {
  system: extends decimal;
  suffix: " ";
  pad: 3 '0'; /* 生成001、002...099、100格式的序号 */
}

/* 应用自定义计数器到有序列表 */
ol#list {
  list-style: custom-leading-zero;
}

/* 如果是用伪元素生成序号的场景,改用自定义计数器 */
ol#list li::before {
  counter-increment: item;
  content: counter(item, custom-leading-zero) " ";
}

方案2:使用浏览器默认序号

如果不需要前置零样式,直接移除自定义计数器的CSS代码,恢复浏览器默认的有序列表序号:

ol#list {
  list-style: decimal; /* 浏览器默认值,可直接覆盖之前的自定义样式 */
}

方案3:确保序号仅对可见项计数

如果需要序号只统计搜索后显示的可见项,调整CSS计数器逻辑,仅对非隐藏的<li>计数:

ol#list {
  counter-reset: visible-item 0;
  list-style: none; /* 隐藏默认序号 */
}

/* 隐藏未匹配的项 */
ol#list li.active {
  display: none;
}

/* 为可见项生成序号 */
ol#list li:not(.active)::before {
  counter-increment: visible-item;
  content: counter(visible-item, custom-leading-zero) " ";
  /* 或者用默认十进制:counter(visible-item) " " */
}

内容的提问来源于stack exchange,提问作者reeman3000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 15:10:07