欢迎光临散文网 会员登陆 & 注册

碎片时间学编程「296]:为指定的选择器创建一个具有指定范围、步长和持续时间的计数器

2023-04-04 12:43 作者:路条编程  | 我要投稿


为指定的选择器创建一个具有指定范围、步长和持续时间的计数器。

  • 检查是否step有正确的标志并相应地更改它。

  • setInterval()与Math.abs()和结合使用Math.floor()以计算每次绘制新文本之间的时间。

  • 使用Document.querySelector(),Element.innerHTML更新所选元素的值。

  • 省略第四个参数 ,step以使用默认步骤1。

  • 省略第五个参数 ,duration以使用默认持续时间2000ms。

JavaScript

const counter = (selector, start, end, step = 1, duration = 2000) => {  let current = start,    _step = (end - start) * step < 0 ? -step : step,    timer = setInterval(() => {      current += _step;      document.querySelector(selector).innerHTML = current;      if (current >= end) document.querySelector(selector).innerHTML = end;      if (current >= end) clearInterval(timer);    }, Math.abs(Math.floor(duration / (end - start))));  return timer;};

示例:

counter('#my-id', 1, 1000, 5, 2000);// Creates a 2-second timer for the element with id="my-id"

更多内容请访问我的网站:https://www.icoderoad.com


碎片时间学编程「296]:为指定的选择器创建一个具有指定范围、步长和持续时间的计数器的评论 (共 条)

分享到微博请遵守国家法律