<!doctype html> <html> <head> <meta charset="utf-8"> <title>链式运动</title> <style> *{ padding:0; margin:0; list-style:none; } #box{ margin:0 auto; background:orange; width:200px; height:200px; opacity:0.3; filter:alpha(opacity:30); margin-bottom:20px; } </style> <script> window.onload=function(){ var div=document.getElementById("box"); div.onmouseover=function(){ change(this,'width',400,function(){ change(this,'height',400); }); } } function getStyle(obj,attr){ if(obj.currentStyle){ return obj.currentStyle[attr]; } else{ return getComputedStyle(obj,false)[attr]; } } function change(obj,attr,target,fn){ clearInterval(obj.timer); obj.timer = setInterval(function(){ var val = 0; if(attr == 'opacity'){ val = Math.round(parseFloat(getStyle(obj,attr))*100); } else{ val = parseInt(getStyle(obj,attr)); } var speed = (target-val)/8; speed = speed>0 ? Math.ceil(speed) : Math.floor(speed); if(val == target){ clearInterval(obj.timer); //判断是否传入了fn if(fn){ fn(); } } else{ if(attr == 'opacity'){ obj.style.filter = 'alpha(opacity:' + val+speed + ')'; obj.style.opacity = (val+speed)/100; } else{ obj.style[attr] = val + speed +"px"; } } },30) } </script> </head> <body> <div id="box"></div> </body> </html>
别直接用This,将this赋值给一个变量,如var that=this;
但是如果是for循环里面的话 this就不能改啊
window.onload=function(){ var div=document.getElementById("box"); div.onmouseover=function(){ change(this,'width',400,function(){ change(this,'height',400); }); } }
这里的外层change()可以传this,但是到了里层change()时,this就代表window对象了。可以改成div