链式运动调用fn的时候,为什么clearInterval(timer)必须在if(fn){fn();}这段代码之前。放在后面就不起作用了。
放在if(fn){fn();}代码之前:
window.onload = function(){ var oLi = document.getElementsByTagName('li'); for(var i=0;i<oLi.length;i++){ oLi[i].timer = null; oLi[i].onmouseover = function(){ var _this = this; startMove(_this,30,'opacity',function(){ startMove(_this,300,'width',function(){ startMove(_this,200,'height'); }); }); } oLi[i].onmouseout = function(){ var _this = this; startMove(_this,100,'height',function(){ startMove(_this,200,'width',function(){ startMove(_this,100,'opacity'); }); }); } } } function startMove(obj,iTarget,attr,fn){ clearInterval(obj.timer); obj.timer = setInterval(function(){ if (attr == 'opacity') { var icur = parseFloat(getStyle(obj,attr)*100); }else{ var icur = parseInt(getStyle(obj,attr)); } var speed = (iTarget-icur)/10; speed = speed>0?Math.ceil(speed):Math.floor(speed); if (icur == iTarget) { clearInterval(obj.timer); if (fn) { fn(); } }else if (attr == 'opacity') { obj.style.filter = 'alpha(opacity:'+(icur+speed)+')'; obj.style.opacity = (icur+speed)/100; }else{ obj.style[attr] = icur + speed + 'px'; } },30) } function getStyle(obj,attr){ if (obj.currentStyle) { return currentStyle[attr]; }else{ return getComputedStyle(obj,false)[attr]; } }
放在if(fn){fn();}代码之后
window.onload = function(){ var oLi = document.getElementsByTagName('li'); for(var i=0;i<oLi.length;i++){ oLi[i].timer = null; oLi[i].onmouseover = function(){ var _this = this; startMove(_this,30,'opacity',function(){ startMove(_this,300,'width',function(){ startMove(_this,200,'height'); }); }); } oLi[i].onmouseout = function(){ var _this = this; startMove(_this,100,'height',function(){ startMove(_this,200,'width',function(){ startMove(_this,100,'opacity'); }); }); } } } function startMove(obj,iTarget,attr,fn){ clearInterval(obj.timer); obj.timer = setInterval(function(){ if (attr == 'opacity') { var icur = parseFloat(getStyle(obj,attr)*100); }else{ var icur = parseInt(getStyle(obj,attr)); } var speed = (iTarget-icur)/10; speed = speed>0?Math.ceil(speed):Math.floor(speed); if (icur == iTarget) { if (fn) { fn(); } clearInterval(obj.timer); }else if (attr == 'opacity') { obj.style.filter = 'alpha(opacity:'+(icur+speed)+')'; obj.style.opacity = (icur+speed)/100; }else{ obj.style[attr] = icur + speed + 'px'; } },30) } function getStyle(obj,attr){ if (obj.currentStyle) { return currentStyle[attr]; }else{ return getComputedStyle(obj,false)[attr]; } }