【发布时间】:2021-06-21 08:22:54
【问题描述】:
我制作了计数动画!但是,设计师要求他们每三个数字取逗号,所以我写了一个代码取逗号,但我认为它应该实时上传,而不仅仅是在最后。我还不习惯 JavaScript。 ㅜㅜ 应该怎么解决呢?
function counterAnimationHandler() {
const counters = document.querySelectorAll('.counter ')
counters.forEach(counter => {
counter.innerText = '0' //set default counter value
const updateCounter = () => {
const target = +counter.getAttribute('data-target') //define increase couter to it's data-target
const count = +counter.innerText //define increase couter on innerText
const increment = target / 200 // define increment as counter increase value / speed
if (count < target) {
counter.innerText = `${Math.ceil(count + increment)}`;
setTimeout(updateCounter, 1);
} else {
counter.innerText = numberWithCommas(target); //if default value is bigger that date-target, show data-target
}
}
updateCounter() //call the function event
})
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
}
counterAnimationHandler();
<div class="counter" data-target="1000000"></div>
【问题讨论】:
-
修复什么?什么没有按预期工作?
it should be uploaded这段代码没有上传任何东西,我错过了什么? -
看来你应该在
if部分做counter.innerText = numberWithCommas(Math.ceil(count + increment))。或者甚至更好,将当前值保存在一个单独的变量中,这样您就不会遇到由const count = +counter.innerText发生的解析引起的解析问题。换句话说,最好不要使用 innerText 值进行解析,将当前值存储在变量中,这样就不需要解析了。
标签: javascript counter