2019-10-25
描述
根据特定的范围、步骤和持续时间在指定的选择器上创建一个计数器。
提示
- 检查
step是否符合要求,并进行相应的修改 - 在
setInterval()中使用Math.abs()和Math.floor()的组合来对每一次绘制计数器的间隔时间进行计算 - 使用
document.querySelector().innerHTML来更新选中元素的值 - 第四个参数
step的默认值为1 - 第五个参数
duration使用的默认值为2000ms
代码
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;
};
示例
为 id="my-id" 的元素创建一个 2 秒的计时器:
counter('#my-id', 1, 1000, 5, 2000);
ME!
链滴