// 多個屬性運動框架? 添加回調函數
functionanimate(obj,json,fn) {// 給誰? ? json
clearInterval(obj.timer);
obj.timer=setInterval(function() {
varflag= true;// 用來判斷是否停止定時器? 一定寫到遍歷的外面
for(varattrinjson){// attr? 屬性? ? json[attr]? 值
//開始遍歷 json
// 計算步長? ? 用 target 位置 減去當前的位置? 除以 10
// console.log(attr);
varcurrent=0;
if(attr=="opacity")
{
current=Math.round(parseInt(getStyle(obj,attr)*100))||0;
console.log(current);
}
else
{
current=parseInt(getStyle(obj,attr));// 數值
}
// console.log(current);
// 目標位置就是? 屬性值
varstep=(json[attr]-current)/10;// 步長? 用目標位置 - 現在的位置 / 10
step=step>0?Math.ceil(step):Math.floor(step);
//判斷透明度
if(attr=="opacity")// 判斷用戶有沒有輸入 opacity
{
if("opacity"inobj.style)// 判斷 我們瀏覽器是否支持opacity
{
// obj.style.opacity
obj.style.opacity=(current+step)/100;
}
else
{// obj.style.filter = alpha(opacity = 30)
obj.style.filter="alpha(opacity = "+(current+step)*10+")";
}
}
else if(attr=="zIndex")
{
obj.style.zIndex=json[attr];
}
else
{
obj.style[attr]=current+step+"px";
}
if(current!=json[attr])// 只要其中一個不滿足條件 就不應該停止定時器? 這句一定遍歷里面
{
flag=? false;
}
}
if(flag)// 用于判斷定時器的條件
{
clearInterval(obj.timer);
//alert("ok了");
if(fn)// 很簡單? 當定時器停止了。 動畫就結束了? 如果有回調,就應該執行回調
{
fn();// 函數名 +? ()? 調用函數? 執行函數
}
}
},10)
}
functiongetStyle(obj,attr) {//? 誰的? ? ? 那個屬性
if(obj.currentStyle)// ie 等
{
returnobj.currentStyle[attr];// 返回傳遞過來的某個屬性
}
else
{
returnwindow.getComputedStyle(obj,null)[attr];// w3c 瀏覽器
}
}
這是本人在學習中寫的簡單的js動效,為了自己更好的學習,從今天(2017/8/18)起,每天堅持發布自己學到的一些東西,這也算是更好地督促自己在前端的路上越走越長吧,畢竟才剛開始,加油咯!Day01