0

function smoothIncrease(startValue, endValue, duration, element) {
  let startTime = null;
  const step = (timestamp) => {
    if (!startTime) startTime = timestamp;
    const progress = Math.min((timestamp - startTime) / duration, 1);
    const currentNumber = Math.floor(progress * (endValue - startValue) + startValue);
    element.innerHTML = currentNumber;
    if (progress < 1) {
      window.requestAnimationFrame(step);
    }
  };
  window.requestAnimationFrame(step);
}

const counter = document.getElementById('counter');
smoothIncrease(0, 100, 2000, counter);

在上面的代码中,smoothIncrease 函数接受四个参数:

  • startValue:起始数字;
  • endValue:目标数字;
  • duration:持续时间(单位为毫秒);
  • element:要更新数字的 HTML 元素。

smoothIncrease 函数内部使用 window.requestAnimationFrame 方法来更新数字,并且在一定的时间内平滑增加数字,直到达到目标数字。在更新数字的过程中,使用 Math.floor 方法将数字取整,以便显示整数。最后,调用 smoothIncrease 函数并传入相应的参数,即可实现数字平滑增加效果。

JavaScript 实现数字平滑增加动画效果

原文地址: https://www.cveoy.top/t/topic/mkrc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录