lorogy
2017-01-11 21:00
//获取obj的属性(样式)attr,如'height'、'width'等 function getStyle(obj, attr) { if(obj.currentStyle) { return obj.currentStyle[attr]; } else { return getComputedStyle(obj,false)[attr]; } } //完整运动动画框架 function motionFrame(obj,json,fn) { clearInterval(obj.timer);//只清除此obj的定时器,不影响其他物体运动 obj.timer=setInterval(function () { var flag=true;//是否json中所有运动都完成 //每30ms所有属性值都会运动一次,+speed //遍历一遍,只要有没达到的flag就为false,否则flag不变仍为true for(var attr in json){ //获得要改变的当前属性值 var curr=0; if (attr=='opacity') { curr=Math.round(parseFloat(getStyle(obj,attr))*100); } else { curr=parseInt(getStyle(obj,attr)); } //改变速度处理 var speed=0; speed=(json[attr]-curr)/8;//根据目标值与当前值的差改变速度,缓冲,差距越大速度越快,差距越小速度越慢 speed=speed>0?Math.ceil(speed):Math.floor(speed);//达到整数值 //检测是否达到目标值 if(curr!=json[attr]){ flag=false;//没到目标,需继续执行 } //obj运动过程 if(attr=='opacity'){ obj.style.filter='alpha(opacity:'+(curr+speed)+')'; obj.style.opacity=(curr+speed); }else{ obj.style[attr]=curr+speed+'px'; } } //多个属性值已经同时改变且达到目标值 if(flag){ clearInterval(obj.timer); //检测是否有回调函数 if(fn){ fn(); } } },30); } window.onload=function () { var list=document.getElementsByTagName('li'); //var timer=null; for (var i=0;i<list.length;i++) { //list[i].timer=null; list[i].onmouseover=function () { motionFrame(list[i],{height:150,width:100,opacity:70}); } list[i].onmouseout=function () { motionFrame(list[i],{height:100,width:150,opacity:30}); } } }
56-62行,如下
for(...){ list[i].index=i //保存i ...=function(){ motionFrame(list[this.index]...);//用this.index替换i } ...=function(){ motionFrame(list[this.index]...);//用this.index替换i
JS动画效果
113920 学习 · 1494 问题
相似问题