使用 JavaScript 实现从 0 到 3000 动态显示数字从小变大效果的方法
----使用 JavaScript 实现从 0 到 3000 动态显示数字从小变大效果的方法
---方法一(这个很好用)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <p id="numberDisplay">0</p> <script> //动态数字效果 - 参数 elDom 元素class '.count_1' 或 id '#count_1',start 开始数字,end结束数字,duration 持续时间 window.setNum = function (elDom, start, end, duration) { let startTimestamp = null; const step = (timestamp) => { if (!startTimestamp) startTimestamp = timestamp; const progress = Math.min((timestamp - startTimestamp) / duration, 1); document.querySelector(elDom).innerHTML = Math.floor(progress * (end - start) + start); if (progress < 1) { window.requestAnimationFrame(step); } }; window.requestAnimationFrame(step); } //调用 setNum('#numberDisplay', 0, 12000), 3000); </script> </body> </html>
---方法二
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <p id="numberDisplay">0</p> <script> window.setNum = function (targetNumber=10,domId) { /*参数说明:targetNumber 终止数字,帮元素ID*/ let number = 0; const interval = setInterval(() => { if (number < targetNumber) { number++; document.getElementById(domId).textContent = number; } else { clearInterval(interval); } }, 0.000000000001); // 每 10 毫秒增加一次数字,可以根据需求调整这个时间间隔 } setNum(3000,'numberDisplay'); </script> </body> </html>