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

如何为值来自CSS变量的CSS伪元素动态添加千位分隔逗号?

需求实现说明

完全可以实现给滚动计数的数字添加千位分隔符的需求,下面给出两种可行的修改方案:

方案1:仅修改CSS代码(无侵入原有逻辑)

不需要修改原有JS、HTML代码,只需要调整CSS规则即可生效,修改后的完整CSS代码如下:

/* 新增:自定义带千位分隔符的计数器规则 */
@counter-style comma-number {
  system: numeric;
  symbols: "0" "1" "2" "3" "4" "5" "6" "7" "8" "9";
  group: 3;
  separator: ",";
  suffix: "";
  fallback: decimal;
}

@property --num {
  syntax: "<integer>";
  initial-value: 0;
  inherits: false;
}

.number-counter {
  transition: --num 3s;
  counter-set: num var(--num);
  font: 800 40px system-ui;
}
/* 替换原有content规则,使用自定义的计数器样式 */
.number-counter::after {
  content: counter(num, comma-number);
}
.number-counter.inView {
  --num: var(--count);
}

方案2:改用JS实现计数逻辑(兼容性更强)

如果需要兼容不支持@counter-style规则的老旧浏览器,可以把计数逻辑迁移到JS中,利用原生toLocaleString()方法自动生成千位分隔符:

  1. 可删除原有CSS中的@property、counter-set、伪元素content相关规则
  2. 修改后的JS代码如下:
setTimeout(function () {
  $('.number-counter').each(function () {
    // 提取目标数值
    const targetCount = parseInt($(this).css('--count'));
    // 用jQuery的animate模拟数值增长
    $({ current: 0 }).animate({ current: targetCount }, {
      duration: 3000,
      step: function () {
        // 每帧更新数值,自动加千位分隔符
        $(this).text(Math.round(this.current).toLocaleString());
      }
    });
  });
}, 500);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 23:24:03