【发布时间】: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