如何为jQuery动画计数器添加千位分隔符,实现数值带逗号格式化
jQuery计数器添加千位分隔符实现方案
你只需要在原有动画的step和complete回调中,将输出的数值做千位格式化处理即可,这里可以直接使用JS原生的toLocaleString()方法快速实现,无需额外引入工具库。
修改后完整JS代码
jQuery(document).ready(function ($) { $(".animated_stats").each(function () { _this = $(this); _this.find('.counter').each(function () { var $this = $(this), countTo = $this.attr('data-count'); $({ countNum: $this.text() }).animate({ countNum: countTo }, { duration: 2000, easing: 'linear', step: function () { // 动画过程中数值添加千位分隔符 $this.text(Math.floor(this.countNum).toLocaleString()); }, complete: function () { // 最终结果添加千位分隔符 $this.text(Number(this.countNum).toLocaleString()); } }); }); }); });
补充说明
如果你不需要动画执行过程中显示千位分隔符,仅需要最终计数结果带分隔符,仅修改complete回调里的输出逻辑即可。原CSS、HTML代码无需调整。
内容的提问来源于stack exchange,提问作者monsaic123
相关产品推荐
相关产品推荐

