简单的 JavaScript 计数器(不使用 jQuery 或其他框架)[关闭]

2023-11-29

我需要一个简单的 JavaScript 计数器,它在页面加载时从 0 开始计数,一直计数到 HTML 中定义的数字。

这是 jQuery 版本...我怎样才能用纯 JavaScript 做同样的事情?

$('.count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="count">200</span>%

忽略缓动,您可以使用创建一个简单的线性计数器window.requestAnimationFrame

let start // set on the first step to the timestamp provided
const el = document.getElementById('count') // get the element
const final = parseInt(el.textContent, 10) // parse out the final number
const duration = 4000 // duration in ms
const step = ts => {
  if (!start) {
    start = ts
  }
  // get the time passed as a fraction of total duration
  let progress = (ts - start) / duration 

  el.textContent = Math.floor(progress * final) // set the text
  if (progress < 1) {
    // if we're not 100% complete, request another animation frame
    requestAnimationFrame(step) 
  }
}

// start the animation
requestAnimationFrame(step)
<span id="count">200</span>%
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

简单的 JavaScript 计数器(不使用 jQuery 或其他框架)[关闭] 的相关文章

随机推荐