答案:使用JavaScript实现数字递增动画可通过setInterval或requestAnimationFrame更新DOM,推荐后者以获得更流畅效果,支持整数、小数、千分位格式化,并可扩展延迟启动等功能。

要实现数字递增动画(也叫数字滚动效果),可以使用 JavaScript 简单编写一个函数,让数字从 0 平滑地增长到目标值。这种效果常用于数据可视化、统计页面或仪表盘中,提升视觉体验。
1. 基础实现:使用 setInterval
通过 setInterval 定期更新元素的文本内容,使数字逐步增加到目标值。
示例代码:
function animateNumber(elementId, start, end, duration) { const element = document.getElementById(elementId); let current = start; const range = end - start; const increment = range > 0 ? Math.ceil(range / (duration / 16)) : 0; // 每帧增加量 const timer = setInterval(() => { current += increment; if (current >= end) { current = end; clearInterval(timer); } element.textContent = current.toLocaleString(); // 格式化千分位 }, 16); // 约 60fps}// 调用示例animateNumber("count", 0, 12345, 2000); // 2秒内从0到12345
2. 更流畅方案:使用 requestAnimationFrame
利用 requestAnimationFrame 实现更平滑、性能更好的动画。
function animateNumberRAF(elementId, endValue, duration = 2000) { const element = document.getElementById(elementId); const startValue = parseInt(element.textContent.replace(/,/g, '')) || 0; const startTime = performance.now();function update(currentTime) {const elapsed = currentTime - startTime;const progress = Math.min(elapsed / duration, 1);
const currentValue = Math.floor( startValue + (endValue - startValue) * progress);element.textContent = currentValue.toLocaleString();if (progress < 1) { requestAnimationFrame(update);}
}
requestAnimationFrame(update);}// 使用方式animateNumberRAF("count", 9876, 1500); // 1.5秒完成
3. 支持小数和格式化
如果需要显示金额、带小数的数值,可扩展函数支持小数位控制。
function animateDecimal(elementId, endValue, decimals = 2, duration = 2000) { const element = document.getElementById(elementId); const startValue = parseFloat(element.textContent) || 0; const startTime = performance.now();function update(time) {const elapsed = time - startTime;const progress = Math.min(elapsed / duration, 1);const currentValue = startValue + (endValue - startValue) * progress;
element.textContent = currentValue.toFixed(decimals);if (progress < 1) { requestAnimationFrame(update);}
}
requestAnimationFrame(update);}// 示例:显示价格增长animateDecimal("price", 123.45, 2, 1000);
4. HTML 结构示例
配合以下 HTML 使用:
00.00
基本上就这些。核心思路是:计算时间进度,动态更新 DOM 内容。使用 requestAnimationFrame 是现代推荐做法,比 setInterval 更高效、更顺滑。根据实际需求可加入千分位分隔、保留小数、延迟启动等增强功能。不复杂但容易忽略细节,比如初始值读取和格式化处理。
以上就是js脚本怎么实现数字递增动画_js数字滚动递增效果脚本编写的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1536159.html
微信扫一扫
支付宝扫一扫