js价格浮动动画函数

效果

初始效果.png

动画变动.png

结束效果.png

代码

<label>价格:2999.00</label>
    <button type="button">打折</button>
    
    <script>
        const label = document.querySelector('label')
        const btn = document.querySelector('button')
        btn.onclick = function(){
            animation(1000,2999,299,(val)=>{
                label.textContent = `价格:${val.toFixed(2)}`
            })
        }
        function animation(duration,from,to,onProgress){
            const dis = to - from
            const speed = dis / duration
            const startTime = Date.now()
            let value = from   //当前的值
            onProgress(value)
            function _run(){
                const now = Date.now()
                const time = now - startTime
                if(time >= duration){
                    value = to
                    onProgress(value)
                    return
                }
                const d = time * speed 
                value = from + d 
                onProgress(value)
                requestAnimationFrame(_run)
            }
            requestAnimationFrame(_run)
        }
    </script>   
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。