碎片時間學(xué)編程「296]:為指定的選擇器創(chuàng)建一個具有指定范圍、步長和持續(xù)時間的計數(shù)器

為指定的選擇器創(chuàng)建一個具有指定范圍、步長和持續(xù)時間的計數(shù)器。
檢查是否step有正確的標(biāo)志并相應(yīng)地更改它。
setInterval()與Math.abs()和結(jié)合使用Math.floor()以計算每次繪制新文本之間的時間。
使用Document.querySelector(),Element.innerHTML更新所選元素的值。
省略第四個參數(shù) ,step以使用默認(rèn)步驟1。
省略第五個參數(shù) ,duration以使用默認(rèn)持續(xù)時間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"
更多內(nèi)容請訪問我的網(wǎng)站:https://www.icoderoad.com