【问题标题】:Javascript count up animation stops counting with comma [duplicate]Javascript计数动画停止用逗号计数[重复]
【发布时间】:2021-11-12 13:37:50
【问题描述】:

我正在尝试在我的页面上使用 javascript 添加计数动画。我已经能够得到一个可行的解决方案,但如果数字有逗号,计数器将停止工作,例如:53,210 计数器将显示53。我怎样才能获得带有逗号的数字的计数器动画?

这是一个代码sn-p:

window.onload = function() {
  runAnimations();
};

// How long you want the animation to take, in ms
const animationDuration = 2000;
// Calculate how long each ‘frame’ should last if we want to update the animation 60 times per second
const frameDuration = 1000 / 60;
// Use that to calculate how many frames we need to complete the animation
const totalFrames = Math.round( animationDuration / frameDuration );
// An ease-out function that slows the count as it progresses
const easeOutQuad = t => t * ( 2 - t );



// The animation function, which takes an Element
const animateCountUp = el => {
    let frame = 0;
    const countTo = parseInt( el.innerHTML, 10 );
    // Start the animation running 60 times per second
    const counter = setInterval( () => {
        frame++;
        // Calculate our progress as a value between 0 and 1
        // Pass that value to our easing function to get our
        // progress on a curve
        const progress = easeOutQuad( frame / totalFrames );
        // Use the progress value to calculate the current count
        const currentCount = Math.round( countTo * progress );

        // If the current count has changed, update the element
        if ( parseInt( el.innerHTML, 10 ) !== currentCount ) {
            el.innerHTML = currentCount;
        }

        // If we’ve reached our last frame, stop the animation
        if ( frame === totalFrames ) {
            clearInterval( counter );
        }
    }, frameDuration );
};


// Run the animation on all elements with a class of ‘countup’
const runAnimations = () => {
    const countupEls = document.querySelectorAll( '.countup' );
    countupEls.forEach( animateCountUp );
};
<ul>
  <li><span class="countup">45</span></li>
  <li><span class="countup">110</span></li>
  <li><span class="countup">53,210</span></li>
</ul>

我希望 HTML 显示完整的 53,210 数量和计数动画。不要停在逗号前的数字。

【问题讨论】:

  • integer 数字没有逗号。您可以以人类可读的格式显示它们,以便更轻松地查看数千和数百万等,但对于计算机,这不是必需的。您可以简单地使用不带分隔符(逗号)的数字进行计算,并用分隔符显示它们以供人们查看

标签: javascript html


【解决方案1】:

在继续执行其余代码之前,您可以尝试从输入中删除 ,。大致如下:

  // get input as string from HTML
  const formattedNumber = el.innerHTML;
  
  // Format as number input (removes commas)
  const inputNumber = formattedNumber.replace(/\,/g,'');
  const countTo = new Number(inputNumber);
  

查看演示

window.onload = function() {
  runAnimations();
};

// How long you want the animation to take, in ms
const animationDuration = 2000;
// Calculate how long each ‘frame’ should last if we want to update the animation 60 times per second
const frameDuration = 1000 / 60;
// Use that to calculate how many frames we need to complete the animation
const totalFrames = Math.round(animationDuration / frameDuration);
// An ease-out function that slows the count as it progresses
const easeOutQuad = t => t * (2 - t);



// The animation function, which takes an Element
const animateCountUp = el => {
  let frame = 0;
  
  // get input as string from HTML
  const formattedNumber = el.innerHTML;
  
  // Format as number input (removes commas)
  const inputNumber = formattedNumber.replace(/\,/g,'');
  const countTo = new Number(inputNumber);
  
  // Start the animation running 60 times per second
  const counter = setInterval(() => {
    frame++;
    // Calculate our progress as a value between 0 and 1
    // Pass that value to our easing function to get our
    // progress on a curve
    const progress = easeOutQuad(frame / totalFrames);
    // Use the progress value to calculate the current count
    const currentCount = Math.round(countTo * progress);

    // If the current count has changed, update the element
    if (parseInt(el.innerHTML, 10) !== currentCount) {
      el.innerHTML = currentCount;
    }

    // If we’ve reached our last frame, stop the animation
    if (frame === totalFrames) {
      clearInterval(counter);
    }
  }, frameDuration);
};


// Run the animation on all elements with a class of ‘countup’
const runAnimations = () => {
  const countupEls = document.querySelectorAll('.countup');
  countupEls.forEach(animateCountUp);
};
<ul>
  <li><span class="countup">45</span></li>
  <li><span class="countup">110</span></li>
  <li><span class="countup">53,210</span></li>
</ul>

【讨论】:

    【解决方案2】:

    需要用逗号解析。 :

    parseInt(el.innerHTML.replace(/,/g, ''), 10)
    

    同样用逗号显示需要跟随换行。

    el.innerHTML = currentCount.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
    

    检查以下代码。

    window.onload = function() {
      runAnimations();
    };
    
    // How long you want the animation to take, in ms
    const animationDuration = 2000;
    // Calculate how long each ‘frame’ should last if we want to update the animation 60 times per second
    const frameDuration = 1000 / 60;
    // Use that to calculate how many frames we need to complete the animation
    const totalFrames = Math.round( animationDuration / frameDuration );
    // An ease-out function that slows the count as it progresses
    const easeOutQuad = t => t * ( 2 - t );
    
    
    
    // The animation function, which takes an Element
    const animateCountUp = el => {
        let frame = 0;
        const countTo = parseInt(el.innerHTML.replace(/,/g, ''), 10);
        // Start the animation running 60 times per second
        const counter = setInterval( () => {
            frame++;
            // Calculate our progress as a value between 0 and 1
            // Pass that value to our easing function to get our
            // progress on a curve
            const progress = easeOutQuad( frame / totalFrames );
            // Use the progress value to calculate the current count
            const currentCount = Math.round( countTo * progress );
    
            // If the current count has changed, update the element
            if ( parseInt( el.innerHTML, 10 ) !== currentCount ) {
                el.innerHTML = currentCount.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
            }
    
            // If we’ve reached our last frame, stop the animation
            if ( frame === totalFrames ) {
                clearInterval( counter );
            }
        }, frameDuration );
    };
    
    
    // Run the animation on all elements with a class of ‘countup’
    const runAnimations = () => {
        const countupEls = document.querySelectorAll( '.countup' );
        countupEls.forEach( animateCountUp );
    };
    <ul>
      <li><span class="countup">45</span></li>
      <li><span class="countup">110</span></li>
      <li><span class="countup">53,210</span></li>
    </ul>

    【讨论】:

      【解决方案3】:

      .toLocaleString('en-US'); 添加到您的const currentCount ,以便动画根据美国数字系统包含逗号。
      See this for .toLocaleString('en-US');

      如果你想在类中也使用逗号,而不是在输入函数值时使用.replace(',', '') 删除逗号。此外,如果值包含超过 1 个逗号而不是像这样使用全局属性 .replace(/\,/g, '')
      See this for Regular expressions

      window.onload = function() {
        runAnimations();
      };
      
      // How long you want the animation to take, in ms
      const animationDuration = 2000;
      // Calculate how long each ‘frame’ should last if we want to update the animation 60 times per second
      const frameDuration = 1000 / 60;
      // Use that to calculate how many frames we need to complete the animation
      const totalFrames = Math.round(animationDuration / frameDuration);
      // An ease-out function that slows the count as it progresses
      const easeOutQuad = t => t * (2 - t);
      
      
      
      // The animation function, which takes an Element
      const animateCountUp = el => {
        let frame = 0;
        const countTo = parseInt(el.innerHTML.replace(/\,/g, ''), 10);
        // Start the animation running 60 times per second
        const counter = setInterval(() => {
          frame++;
          // Calculate our progress as a value between 0 and 1
          // Pass that value to our easing function to get our
          // progress on a curve
          const progress = easeOutQuad(frame / totalFrames);
          // Use the progress value to calculate the current count
          const currentCount = Math.round(countTo * progress).toLocaleString('en-US');;
      
          // If the current count has changed, update the element
          if (parseInt(el.innerHTML, 10) !== currentCount) {
            el.innerHTML = currentCount;
          }
      
          // If we’ve reached our last frame, stop the animation
          if (frame === totalFrames) {
            clearInterval(counter);
          }
        }, frameDuration);
      };
      
      
      // Run the animation on all elements with a class of ‘countup’
      const runAnimations = () => {
        const countupEls = document.querySelectorAll('.countup');
        countupEls.forEach(animateCountUp);
      };
      <ul>
        <li><span class="countup">45</span></li>
        <li><span class="countup">110</span></li>
        <li><span class="countup">53,210</span></li>
        <li><span class="countup">5,3,2,1,0</span></li>
        <li><span class="countup">53,215480</span></li>
      </ul>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-15
        • 1970-01-01
        相关资源
        最近更新 更多