通过js动态实现数字改变效果
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="price">1999</div>
<button id="btn">新增</button>
</body>
<script type="text/javascript">
document.querySelector("#btn").addEventListener("click", () => {
animation(1000, 1999, 199);
})
function animation(duration, from, to) {
const dis = to - from;
const speed = dis / duration;
const startTime = Date.now();
let value = from; //当前值
function _run() {
const now = Date.now();
const time = now - startTime;
if (time >= duration) {
value = to;
document.querySelector("#price").innerText = value
return false;
}
const d = Math.round(time * speed);
value = from + d;
document.querySelector("#price").innerText = value
requestAnimationFrame(_run)
}
requestAnimationFrame(_run)
}
</script>
</html>