1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 <style> 7 * { 8 margin: 0; 9 padding: 0; 10 } 11 12 #box { 13 100px; 14 height: 100px; 15 background-color: red; 16 position: absolute; 17 } 18 </style> 19 </head> 20 <body> 21 <button id="btn">往右走</button> 22 <div id="box"></div> 23 <script src="js/MyTool.js"></script> 24 <script> 25 window.addEventListener('load', function (ev) { 26 // 1. 变量 27 var target = 800, timer = null, speed = 0, box = myTool.$('box'); 28 29 // 2. 监听点击 30 myTool.$('btn').addEventListener('click', function () { 31 // 2.1 先清后设 32 clearInterval(timer); 33 34 // 2.2 设置定时器 35 // begin = begin + (end - begin) * 0.2 36 // 步长 37 timer = setInterval(function () { 38 // 2.3 求出步长 39 speed = (target - box.offsetLeft) * 0.2; 40 41 console.log('之前:' + speed); 42 speed = Math.ceil(speed); 43 console.log('之后:' + speed); 44 45 // 2.4 动起来 46 box.style.left = box.offsetLeft + speed + 'px'; 47 box.innerText = box.offsetLeft; 48 49 // 2.5 清除定时器 50 if(box.offsetLeft === target){ 51 clearInterval(timer); 52 } 53 }, 20); 54 }); 55 }); 56 </script> 57 </body> 58 </html>
1 <script> 2 window.addEventListener('load', function (ev) { 3 var box = myTool.$('box'); 4 5 // 向右走 6 myTool.$('btn').addEventListener('click', function () { 7 buffer(box, 800); 8 }); 9 10 // 向左走 11 myTool.$('btn1').addEventListener('click', function () { 12 buffer(box, 200); 13 }); 14 }); 15 16 17 18 /** 19 * 缓动东环函数 20 * @param {Object}eleObj 21 * @param {Number}target 22 */ 23 function buffer(eleObj, target) { 24 // 1.1 先清后设 25 clearInterval(eleObj.timer); 26 27 // 1.2 定义变量 28 var speed = 0; 29 30 // 1.2 设置定时器 31 eleObj.timer = setInterval(function () { 32 // 2.3 求出步长 33 speed = (target - eleObj.offsetLeft) * 0.2; 34 speed = (target > eleObj.offsetLeft) ? Math.ceil(speed) : Math.floor(speed); 35 36 // 2.4 动起来 37 eleObj.style.left = eleObj.offsetLeft + speed + 'px'; 38 eleObj.innerText = eleObj.offsetLeft; 39 40 // 2.5 清除定时器 41 if(eleObj.offsetLeft === target){ 42 clearInterval(eleObj.timer); 43 } 44 }, 20); 45 } 46 </script>
封装缓存动画