首页 > Web开发 > 详细

JS 指定选择器创建具有指定范围,步长和持续时间的计数器

时间:2020-03-18 09:55:24      阅读:70      评论:0      收藏:0      [点我收藏+]
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); 
// 让 `id=“my-id”`的元素创建一个2秒计时器

 

JS 指定选择器创建具有指定范围,步长和持续时间的计数器

原文:https://www.cnblogs.com/wkk2020/p/12515134.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!