css3動畫實現數字動態增加

维维WW發表於2024-07-01

要實現數字的動態增加效果,可以使用CSS3的@keyframes規則來建立動畫,並使用JavaScript來更新數字。以下是一個簡單的實現示例:

HTML:

<div id="counter" class="counter">0</div>

CSS:

.counter {
  /* 初始樣式 */
}
 
@keyframes increaseNumber {
  from { opacity: 0; transform: translateY(-10px); }
  to { opacity: 1; transform: translateY(0); }
}
 
.counter.animated {
  animation: increaseNumber 0.5s ease-out forwards;
}

JS

function animateValue(obj, start, end, duration) {
    let startTimestamp = null;
    const step = (timestamp) => {
        if (!startTimestamp) startTimestamp = timestamp;
        const progress = Math.min((timestamp - startTimestamp) / duration, 1);
        obj.innerHTML = Math.floor(progress * (end - start) + start);
        if (progress < 1) {
            window.requestAnimationFrame(step);
        } else {
            obj.classList.remove('animated');
        }
    };
    obj.classList.add('animated');
    window.requestAnimationFrame(step);
}
 
const counter = document.getElementById('counter');
animateValue(counter, 0, 100, 2000); // 從0增加到100,過程持續2000毫秒

相關文章