如何创建一个从零到HTML中包含的元素的Javascript PURE动画?



我正在尝试创建一个脚本,该脚本从零计数到将通过PHP馈送的数字,例如我的HTML是

<h1 class = "myClass"> 500 </h1>
<h1 class = "myClass"> 424 </h1>
<h1 class = "myClass"> 424 </h1>

我想检索包含特定类的元素的值,并从零计数到它们自己。

但是我希望它用Javascript完成,我已经看到了一些Jquery插件,但我想在javascript中做同样的事情,就像这个例子一样:https://codepen.io/shivasurya/pen/FatiB

细节,对于小值和大值同时结束计数会很有趣。

我已经尝试过类似的东西:

function ng_count_number_animation (element) {
let select = window.document.querySelectorAll (element);
let start = 0;
let i;
for (i = 0; i <select.length; i ++) {
for (let y = 0; y <= Number (select [i] .innerHTML); y ++) {
select [i] .innerHTML = y;
}
}
}
ng_count_number_animation (". ng_count_number");

但它永远不会起作用,我也使用 Javascript setinterval 来间隔计数,但它也不起作用,所有类的结果总是为零。

您可以使用requestAnimationFrame((来实现这一点,以尽可能频繁地执行函数。我的代码不是最有效的,但我认为它应该很容易理解:

//retrieve all counters from body
let counters = document.getElementsByClassName('myClass');
//retrieve all counter value
let vals = Array.from(counters).map(x => Number(x.innerHTML));
//convert counters element collection to an array
counters = Array.from(counters);
//loop through all counters
counters.forEach(el => {
//set counter to 0
el.innerHTML = '0';
//set 'internal' counter to 0 -> obviously this isn't super efficient
//could be faster if you used an array instead
el.counter = 0;
});
//execute this function as often as possible using requestAnimationFrame()
let update = () => {
//loop through all counters
counters.forEach((el, i) => {
//add one to 'internal counter'
el.counter += 1;
//update counter display value min(max, currentVal + 1)
el.innerHTML = Math.min(vals[i], el.counter);
});
requestAnimationFrame(update);
}
update();
<h1 class = "myClass"> 500 </h1>
<h1 class = "myClass"> 424 </h1>
<h1 class = "myClass"> 424 </h1>

最新更新