【问题标题】:How to create a Javascript PURE animation that counts from zero to the Element contained in the HTML? [duplicate]如何创建从零计数到 HTML 中包含的元素的 Javascript PURE 动画? [复制]
【发布时间】:2019-09-16 08:20:47
【问题描述】:

我正在尝试创建一个从零计数到将通过 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 来间隔计数,但它也不起作用,所有类的结果总是为零。

【问题讨论】:

  • 不,您不能选择多个元素并一次为它们设置动画,而不必多次调用该函数。
  • “对于小值和较大值,计数同时结束会很有趣” - 如果您希望它们开始并让它们结束同时,那么您当然必须相应地修改间隔或增量步长……

标签: javascript php html css animation


【解决方案1】:

您可以使用 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>

【讨论】:

  • 但是有没有办法让计数同时停止而不管位数?例如:100、1000、100000,动画是否同时停止?
  • 您可以通过使用不同的增量值或不同的速度来做到这一点
猜你喜欢
  • 1970-01-01
  • 2013-02-01
  • 1970-01-01
  • 2021-03-05
  • 2015-12-24
  • 1970-01-01
  • 2018-07-28
  • 1970-01-01
  • 2017-09-29
相关资源
最近更新 更多