首页 > 其他分享 >css3动画实现数字动态增加

css3动画实现数字动态增加

时间:2024-07-01 15:58:04浏览次数:1  
标签:css3 动画 obj timestamp startTimestamp counter start progress 动态

要实现数字的动态增加效果,可以使用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毫秒

 

标签:css3,动画,obj,timestamp,startTimestamp,counter,start,progress,动态
From: https://www.cnblogs.com/tanweiwei/p/18278228

相关文章