为滚动触发的数字动画计数器添加千位分隔符
滚动触发数字动画计数器(带千位分隔符)
问题解决核心
把数字和后缀符号(如+、%)拆分处理,避免带逗号的字符串触发NaN,同时用JavaScript原生方法实现千位分隔,无需手动拼接。
修改后的完整代码
<script> function inVisible(element) { // 检测元素是否在视口内 var WindowTop = $(window).scrollTop(); var WindowBottom = WindowTop + $(window).height(); var ElementTop = element.offset().top; var ElementBottom = ElementTop + element.height(); // 元素可见时启动动画 if ((ElementBottom <= WindowBottom) && ElementTop >= WindowTop) animate(element); } function animate(element) { if (!element.hasClass('ms-animated')) { // 将max值转为数字,避免字符串导致NaN var maxval = parseInt(element.data('max'), 10); // 拆分初始内容:数字部分 + 后缀符号 var initialContent = element.html().trim(); var match = initialContent.match(/^(\d+)(.*)$/); var initialNum = match ? parseInt(match[1], 10) : 0; var suffix = match ? match[2] : ''; element.addClass("ms-animated"); $({ countNum: initialNum }).animate({ countNum: maxval }, { duration: 2000, easing: 'linear', step: function() { // 给当前数字添加千位分隔符后拼接后缀 element.html(Math.floor(this.countNum).toLocaleString() + suffix); }, complete: function() { // 动画结束后显示最终带千位分隔的数字 element.html(this.countNum.toLocaleString() + suffix); } }); } } $(function() { $(window).scroll(function() { $("h2[data-max]").each(function() { inVisible($(this)); }); }) }); </script>
关键修改说明
- 拆分数字与符号:用正则
/^(\d+)(.*)$/把初始内容(如0%、0+)拆成数字和后缀两部分,避免符号干扰数字计算。 - 确保数值类型正确:通过
parseInt把data-max的属性值转为整数,防止字符串格式导致动画异常。 - 千位分隔符实现:使用
toLocaleString()方法自动添加千位分隔符,比手动拼接逗号更稳定可靠。 - HTML使用示例:你的h2标签无需提前加逗号,直接这样写即可:
<h2 data-max="1234">0+</h2> <h2 data-max="56789">0%</h2>
内容的提问来源于stack exchange,提问作者laurlaurfl234
相关产品推荐
相关产品推荐

