在前面有多次用到了定时器来生成动画,通常的做法是已知其实值和结束值,给出了运动步长即可,如下所示:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> *{ margin: 0; padding: 0; } #box{ width: 100px; height: 100px; background-color: red; position: absolute; } </style> </head> <body> <button id="btn">往右走</button> <div id="box"></div> <script> function $(id) { return typeof id === "string" ? document.getElementById(id) : null; } window.onload = function () { // 0. 变量 var target = 400, timer = null; var box = $("box"); // 1. 监听按钮的点击 $("btn").onclick = function () { // 1.1 清除定时器 clearInterval(timer); // 1.2 设置定时器 timer = setInterval(function () { // 1.3 求出步长 var speed = (target - box.offsetLeft) * 0.2; console.log(speed); // 向上取整 speed = Math.ceil(speed); // 1.4 动起来 box.style.left = box.offsetLeft + speed + "px"; box.innerText = box.offsetLeft; // 1.5 判断 if(box.offsetLeft === target){ clearInterval(timer); } }, 20); }; } </script> </body> </html>
在上面的例子中,目标值是右移动400px,我们给出步长后,通过定时器为元素赋值,让其运动起来,但在实际运动中,我们通常的运动除了上面的向右移动,还有向左,向上或者其他的运动,这时,我们需要将上面的代码稍作修改。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> *{ margin: 0; padding: 0; } #box{ width: 100px; height: 100px; background-color: red; position: absolute; } </style> </head> <body> <button id="btn">往右走</button> <button id="btn1">往左走</button> <div id="box"></div> <script> function $(id) { return typeof id === "string" ? document.getElementById(id) : null; } window.onload = function () { var box = $("box"); $("btn").onclick = function () { buffer(box, 800); }; $("btn1").onclick = function () { buffer(box, 200); }; }; function buffer(obj, target) { clearInterval(obj.timer); obj.timer = setInterval(function () { // 求出步长 var speed = (target - obj.offsetLeft) * 0.2; // 判断是否向上取整 speed = (target > obj.offsetLeft) ? Math.ceil(speed) : Math.floor(speed); obj.style.left = obj.offsetLeft + speed + "px"; obj.innerText = obj.offsetLeft; if(obj.offsetLeft === target){ clearInterval(obj.timer); } }, 20); } </script> </body> </html>
这个例子与上面不同的是既有向左走的,又有向右走的,但是不管向左还是向右运动,改变的都是元素距离左边的距离。所以我们可以将共用的部分单独提取出来,再针对不同的方向传入不同的目标值即可了。