JS---封装缓动(变速)动画函数---增加任意多个属性&增加回调函数
封装缓动(变速)动画函数---增加任意多个属性&增加回调函数
回掉函数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>
相关推荐
angqiuli 2020-04-16
88274956 2020-11-03
runner 2020-09-01
梦的天空 2020-08-25
移动开发与培训 2020-08-16
ReunionIsland 2020-08-16
lyqdanang 2020-08-16
MyNameIsXiaoLai 2020-07-08
星辰的笔记 2020-07-04
csstpeixun 2020-06-28
letheashura 2020-06-26
liaoxuewu 2020-06-26
sunzhihaofuture 2020-06-21
FEvivi 2020-06-16
坚持着执着 2020-06-16
waterv 2020-06-14
xiaoge00 2020-06-14
firejq 2020-06-14
firstboy0 2020-06-14
e度空间 2020-06-12
zhongweinan 2020-06-10