1.js封装claerAnimate
function claerAnimate(options) {
var from = options.from;
var to = options.to;
var totalMS = options.tatolMS || 1000;
var duration = options.duration || 15;
var times = Math.floor(totalMS / duration);
var dis = (to - from) / times;
var indexId = 0;
var timer = setInterval(function () {
from += dis;
indexId++;
if (indexId >= times) {
from = to;
clearInterval(timer);
options.onend && options.onend();
}
options.onmove && options.onmove(from);
}, duration);
}
2.简单的调用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>活动价:¥<span>500.00</span></h1>
<script src="./animate.js"></script>
<script>
var span = document.querySelector("span");
claerAnimate({
from: 500,
to: 99,
totalMS: 3000,
duration: 100,
onmove: function (n) {
span.innerHTML = n.toFixed(2);
},
onend: function () {
span.style.color = "red";
},
});
</script>
</body>
</html>