没用Math.round()方法,为什么没问题
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>javascript_move</title> <style> *{margin: 0;padding: 0} #box4{background-color: green;width: 200px;height: 200px;opacity: 0.3;margin: 20px;float: left;} </style> <script type="text/javascript"> window.onload=function(){ var movepart3=document.getElementsByTagName('div'); for(var i=0;i<movepart3.length;i++){ movepart3[i].timer=null; movepart3[i].onmouseover=function(){ startmove3(this,100,'opacity'); } movepart3[i].onmouseout=function(){ startmove3(this,30,'opacity'); } } } function startmove3(box3,target,attr){ clearInterval(box3.timer); box3.timer=setInterval(function(){ var a=0; if(attr=='opacity'){ a=parseFloat(getStyle(box3,attr))*100;//这里没用Math.round(); }else{ a=parseInt(getStyle(box3,attr)); } var speed=(target-a)/8; speed=speed>0?Math.ceil(speed):Math.floor(speed); if(a==target){ clearInterval(box3.timer); } else{ if(attr=='opacity'){ box3.style.opacity=(a+speed)/100; console.log(box3.style.opacity);//我这里加了断点,测试opacity当前值 box3.style.filter="alpha(opacity="+(a+speed)+")"; } else{ box3.style[attr]=a+speed+"px"; } } },30); } function getStyle(obj,attr){ if(obj.currentStyle){ return obj.currentStyle[attr]; }else{ return getComputedStyle(obj,false)[attr]; } } </script> </head> <body> <div id="box4"></div> <div id="box4"></div> <div id="box4"></div> <div id="box4"></div> </body> </html>
没用Math.round()竟然没问题,奇了怪了,什么情况~?变量名有点奇怪,请答题的大大将就下。代码复制另存html就可以运行了。
下面是console.log()测试的opacity值: