<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 //當(dāng)前的值
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>