<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> *{ margin:0; padding:0; } #div1{ width: 400px; height: 100px; background: #5f5290; position: relative; left: -400px; margin-bottom: 20px; opacity: 0.3; } #div2{ width: 20px; height: 60px; background: #8e7dbf; position: absolute; right: -20px; top:20px; } </style> </head> <body> <div id="div1"> <div id="div2">详情</div> </div> <script type="text/javascript"> window.onload=function(){ var div1=document.getElementById("div1"); var div2=document.getElementById("div2"); div1.onmouseover=function(){ start(0); changeOpacity(100); } div1.onmouseout=function(){ start(-400); changeOpacity(30); } var i=null; function start(target){ clearInterval(i); var speed=0; i=setInterval(function(){ if(div1.offsetLeft<target){ speed=10; }else{ speed=-10; } if(div1.offsetLeft==target){ clearInterval(i) }else{div1.style.left=div1.offsetLeft+speed+"px"; } } ,20) } var timer=null; var alpha=30; function changeOpacity(target){ clearInterval(timer); var speed=0; timer=setInterval(function(){ if(alpha<target){ speed=10; }else{ speed=-10; } if(alpha==target){ clearInterval(timer) }else{ alpha+=speed; div1.style.opacity=alpha/100; }},100) } } </script> </body> </html>
全局变量局部变量可以获取到,反之就不行
因为onmouseover是从30到100,而onmouseout是从100到30.这两个事件都调用同一个函数changeOpacity。因为一开始我们肯定是先进行onmouseover事件的,所以var alpha=30;只是为了方便第一次初始化,应该是全局变量。如果把它放到里面就变成了局部变量,这样的话就会每次调用函数changeOpacity时都会进行var alpha=30;操作导致alpha的值一直为30,而你的函数内有这样一个判断if(alpha==target){clearInterval(timer);},而onmouseout事件的目标值(target)为30,这样就会导致直接关闭定时器不进行onmouseout事件。