手写简单的缓动动画框架(js动效)

2017-08-18  本文已影响0人  信者云也

// 多个属性运动框架  添加回调函数

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

上一篇下一篇

猜你喜欢

热点阅读