我如何在香草 javascript 中用逗号编码计数动画?

how can I code counting animation with comma in vanilla javascript?

我制作了数数动画!但是,Designer要求他们每三位取逗号,所以我写了一个取逗号的代码,但是我觉得应该实时上传,而不是最后才上传。我还不习惯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>

我建议您使用原始(未格式化)数字为 count 保留一个不同的变量,然后确保将对 UI 的每个更新都用 numberWithCommas 包装起来。

function counterAnimationHandler() {
  const counters = document.querySelectorAll('.counter ')
  counters.forEach(counter => {
    counter.innerText = '0' //set default counter value
    counter.dataset.count = 0;
    const updateCounter = () => {
      const target = +counter.getAttribute('data-target') //define increase couter to it's data-target
      const count = +counter.dataset.count //define increase couter on innerText

      const increment = target / 200 // define increment as counter increase value / speed

      if (count < target) {
        const newCount = Math.ceil(count + increment);
        counter.dataset.count = newCount;
        counter.innerText = numberWithCommas(newCount);
        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>