sport.js
// obj 运动的元素 // target 目标值 // attr 操作的属性 function move(obj, target, attr) { clearInterval(obj.timer); var speed = 0; if (attr === "opacity") { current = parseFloat(getStyle(obj, attr)) * 100; // "1"*100 speed = target - current > 0 ? 1 : -1; } else { current = parseInt(getStyle(obj, attr)); speed = target - current > 0 ? 10 : -10; } obj.timer = setInterval(() => { if (attr === "opacity") { current = parseFloat(getStyle(obj, attr)) * 100; // "1"*100 obj.style[attr] = (current + speed) / 100; } else { current = parseInt(getStyle(obj, attr)); obj.style[attr] = (current + speed) + "px"; } if (Math.abs(target - current) < Math.abs(speed)) { if (attr === "opacity") { obj.style[attr] = target / 100; } else { obj.style[attr] = target + "px"; } return clearInterval(obj.timer); } }, 30); } // 300px 200px //100+10+10+10 function getStyle(obj, attr) { if (window.getComputedStyle) { return getComputedStyle(obj, false)[attr]; } else { return obj.currentStyle[attr]; } }
sport2.js
// obj 运动的元素 // target 目标值 // attr 操作的属性 function move(obj, target, attr,callback) { clearInterval(obj.timer); var speed = 0; if (attr === "opacity") { current = parseFloat(getStyle(obj, attr)) * 100; // "1"*100 speed = target - current > 0 ? 1 : -1; } else { current = parseInt(getStyle(obj, attr)); speed = target - current > 0 ? 10 : -10; } obj.timer = setInterval(() => { if (attr === "opacity") { current = parseFloat(getStyle(obj, attr)) * 100; // "1"*100 obj.style[attr] = (current + speed) / 100; } else { current = parseInt(getStyle(obj, attr)); obj.style[attr] = (current + speed) + "px"; } if (Math.abs(target - current) < Math.abs(speed)) { if (attr === "opacity") { obj.style[attr] = target / 100; } else { obj.style[attr] = target + "px"; } clearInterval(obj.timer); if(callback) { callback(); } } }, 30); } // 300px 200px //100+10+10+10 function getStyle(obj, attr) { if (window.getComputedStyle) { return getComputedStyle(obj, false)[attr]; } else { return obj.currentStyle[attr]; } }
05animate.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .box { width: 200px; height: 100px; background-color: red; position: relative; } </style> </head> <body> <div class="box" id="box"></div> <script src="sport2.js"></script> <script> var box = document.querySelector("#box"); //move(box,200,"height"); move(box,300,"width",function() { //console.log("动画完毕"); move(box,200,"height",function() { move(box,300,"left"); }); }); // 同时改变属性? json {} </script> </body> </html>