js封裝函數

// fn 回調函數—>把函數當作參數使用
function animate(element,json,fn){
//優化1.先清理定時器
clearInterval(element.timeId);
element.timeId=setInterval(function () {
var flay=true;//假設全部到達目標位置
for (var attr in json){
//1.獲取當前的位置
var current=parseInt(getStyle(element,attr));// attr -->height 200px 要化整
//目標的值
var target=json[attr];
//2.設置div每次移動多少像素
var step=(target-current)/10;
//優化2. 判斷向右移還是向左移
step=step>0 ? Math.ceil(step): Math.floor(step);
//3.每次移動後的距離
current+=step;
//賦值
element.style[attr]=current+“px”;
//如果 有一個當前的位置 不等於 目標位置
//讓flay = false
if (current!=target) {
flay=false;
}
}
//循環過後,如果flay爲true,證明都到達了目標位置, 則清除定時器
if (flay){
//清除定時器
clearInterval(element.timeId);

        //所有的屬性達到目標後才調用這個函數,
        //判斷:如果用戶傳了fn ,則調用
        if (fn){
            fn();
        }
    }

    //測試代碼
   // console.log("目標位置" + target + ",當前位置" + current + ",每次移動的步數" + step);
},20)

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章