我需要一个简单的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>%
&#13;
答案 0 :(得分:2)
忽略缓动,您可以使用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>%
答案 1 :(得分:0)
function counter() {
var i = 0;
var element = document.getElementById("output");
var funcNameHere = function() {
element.innerHTML = `${i}%`
if (i == 100) clearInterval(this);
else console.log('Currently at ' + (i++));
};
// This block will be executed 100 times.
setInterval(funcNameHere, 70);
funcNameHere();
} // End
&#13;
<div id="output">0%
</div>
<button onclick="counter();">
start
</button>
&#13;