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

WordPress中如何为JS动画计数数字添加千分位逗号?

为jQuery数字动画添加千分位逗号格式

要实现带千分位逗号的数字计数动画,只需要在更新数字文本时对数字做格式化处理即可。你可以直接使用JavaScript原生的toLocaleString()方法,它能自动为数字添加千分位分隔符,无需手动编写正则规则。

修改后的完整代码如下:

<?php
add_action( 'wp_head', function () { 
?>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $({ countNum: $('.code').html() }).animate({ countNum: 6000 }, {
            duration: 4000,
            easing: 'linear',
            step: function () {
                // 格式化数字并添加"+"后缀
                $('.code').html(Math.floor(this.countNum).toLocaleString() + "+");
            },
            complete: function () {
                // 动画结束后格式化最终数字
                $('.code').html(this.countNum.toLocaleString() + "+");
                //alert('finished');
            }
        });
    </script>
<?php } ); ?>

关键修改说明

  • 在step方法中,对Math.floor(this.countNum)调用toLocaleString(),为实时计数的数字添加千分位分隔符。
  • 在complete方法中,同样对最终目标数字this.countNum执行格式化操作,保证最终显示的数字也带有千分位。

如果需要指定特定区域的千分位格式(比如强制使用美式英文格式),可以给方法传入区域参数:Math.floor(this.countNum).toLocaleString('en-US'),默认情况下浏览器会根据系统设置自动适配,一般无需额外指定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 14:55:18