ELEMENTS爱乐冬雨 2019-12-20
回掉函数fn,在所有元素到达目的位置后,判断是否传入一个函数,有就调用 if(fn){fn()};
这样一次点击,产生多个动画
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>title</title> <style> * { margin: 0; padding: 0; } div { margin-top: 30px; width: 200px; height: 100px; background-color: green; position: absolute; left: 0; top: 0; } </style> </head> <body> <input type="button" value="移动到400px" id="btn1" /> <div id="dv"> </div> <script src="common.js"></script> <script> //点击按钮,改变宽度到达一个目标值,高度到达一个目标值 //获取任意一个元素的任意一个属性的当前的值---当前属性的位置值 function getStyle(element, attr) { return window.getComputedStyle ? window.getComputedStyle(element, null)[attr] : element.currentStyle[attr] || 0; } //element---元素 //json---对象---多个属性及多个目标值 //fn---函数 function animate(element, json, fn) { clearInterval(element.timeId); element.timeId = setInterval(function () { var flag = true; for (var attr in json) { var current = parseInt(getStyle(element, attr)); var target = json[attr]; var step = (target - current) / 10; step = step > 0 ? Math.ceil(step) : Math.floor(step); current += step; element.style[attr] = current + "px"; if (current != target) { flag = false; } } if (flag) { clearInterval(element.timeId); if (fn) { fn(); } } //测试代码 console.log("目标:" + target + ",当前:" + current + ",每次移动的步数" + step); }, 20) } my$("btn1").onclick = function () { var json1 = { "width": 400, "height": 200, "left": 500, "top": 80 }; animate(my$("dv"), json1, function () { var json2 = { "width": 200, "height": 100, "left": 200, "top": 120 }; animate(my$("dv"), json2, function () { var json3 = { "width": 400, "height": 300, "left": 300, "top": 80 }; animate(my$("dv"), json3); }); }); }; </script> </body> </html>