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