JS為變速移動新增任意多個屬性值包括回撥函式
阿新 • • 發佈:2018-11-19
//封裝新增任意多個屬性的函式 //fn這個引數是為這個函式新增的回撥函式 function changeAll(ele,json,fn){ //每次都清除一次定時器 clearInterval(ele.timed); //設定定時器 ele.timed=setInterval(function() { var flag=true; //遍歷json中的資料 //attr為json中的屬性名,json[attr]為json中的屬性值 for(var attr in json) { //獲取當前屬性值 var now = parseInt(getStyle(ele, attr)); //設定每次改變的值 var step = (json[attr] - now) / 10; step = step > 0 ? Math.ceil(step) : Math.floor(step); now += step; //設定每次改變之後的樣式 ele.style[attr] = now + 'px'; if (now !=json[attr]) { flag=false; } } if(flag){ //當所有的屬性值都達到了自己設定的目標的時候,清除定時器 clearInterval(ele.timed); //在上面的條件達到的時候,執行回撥函式 if(fn){ fn(); } } },20); }
案例:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { margin: 0; padding: 0; } div { width: 200px; height: 100px; background-color: green; position: absolute; left: 0; top: 20px; } </style> </head> <body> <input type="button" value="改變div樣式" id="btn" /> <div id="dv"></div> <script src="js/common.js"></script> <script src="js/getStyle.js"></script> <script src="js/changespeadAll.js"></script> <script> var json={ 'left':150, 'top':150, 'width':300, 'height':200 }; var json2={ 'left':300, 'top':300, 'width':200, 'height':100 }; var json3={ 'left':50, 'top':50, 'width':50, 'height':30 }; //獲取div var dv = my$('dv'); //設定按鈕點選事件 my$('btn').onclick=function(){ changeAll(dv,json,function(){ changeAll(dv,json2,function(){ changeAll(dv,json3); }); }); }; /*//封裝新增任意多個屬性的函式 function changeAll(ele,json){ //每次都清除一次定時器 clearInterval(ele.timed); //設定定時器 ele.timed=setInterval(function() { var flag=true; //遍歷json中的資料 //attr為json中的屬性名,json[attr]為json中的屬性值 for(var attr in json) { //獲取當前屬性值 var now = parseInt(getStyle(ele, attr)); //設定每次改變的值 var step = (json[attr] - now) / 10; step = step > 0 ? Math.ceil(step) : Math.floor(step); now += step; //設定每次改變之後的樣式 ele.style[attr] = now + 'px'; if (now !=json[attr]) { flag=false; } } if(flag){ clearInterval(ele.timed); } },20); }*/ </script> </body> </html>
實現div的三次過渡動畫