javascript - 简单的 JavaScript 计数器(不使用 jQuery 或其他框架)

标签 javascript

我需要一个简单的 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>%

关于javascript - 简单的 JavaScript 计数器(不使用 jQuery 或其他框架),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50245161/

相关文章:

javascript - 如何在 Linux 中作为守护进程运行的二进制 nodejs 应用程序中运行 exec?

javascript - 使用 PHP 获取数组计数,在 HTML 中插入计数并使用 Javascript 获取

javascript - div 出现几秒钟并在 jquery/javascript 中消失?

javascript - 使用 Javascript 创建 html 表不起作用

javascript - 为什么这个JS倒计时不起作用?

javascript - 检测段落中一个或多个单词的子串

c# - 如何动态加载css到html中?

javascript - 未知错误: cannot focus element

javascript - 在选择上使用 jQuery 克隆 HTML DIV

javascript - 使用媒体查询调整图像大小