請問這個BUG是什么情況?http://www.xianlaiwan.cn/video/2879
<!DOCTYPE?html> <html> <head> <meta?charset="UTF-8"> <title></title> <style?type="text/css"> *?{ margin:?0; padding:?0; } #divs?{ height:?260px; width:?160px; background-color:?antiquewhite; border-radius:?10px; position:?relative; left:?-160px; } #spans?{ height:?100px; width:?20px; background-color:?cornflowerblue; border-radius:?5px; position:?absolute; left:?160px; margin-left:?1px; box-shadow:?5px?2px?10px?cornflowerblue; border:?1px?solid?white; } #div_opacity?{ height:?100px; width:?100px; background-color:?brown; border-radius:?100px; box-shadow:?5px?2px?10px?#A52A2A; border:?1px?solid?white; opacity:?0.1; } </style> <script?type="text/javascript"> window.onload?=?function()?{ var?div?=?document.getElementById("divs"), span?=?document.getElementById("spans"), div_o?=?document.getElementById("div_opacity"); var?speed?=?5; div.onmouseover?=?function()?{ star_1(speed,?div,?0); } div.onmouseleave?=?function()?{ star_1(speed,?div,?-160); } } var?timer?=?null; function?star_1(speed,?div,?itarget)?{ clearInterval(timer); timer?=?setInterval(function()?{ if?(div.offsetLeft?==?itarget)?{ clearInterval(timer); }?else?{ if?(itarget?==?0)?{ speed?=?speed; }?else?if?(itarget<0)?{ speed?=?-speed; } if?(div.offsetLeft?>?-160?/?2)?{ speed?=?speed?*?3; }?else?{ speed?=?speed; } div.style.left?=?div.offsetLeft?+?speed?+?"px"; //解決抖動 if?(div.offsetLeft?>?0)?{ clearInterval(timer); div.style.left?=?"0px"; } if?(div.offsetLeft?<?-160)?{ clearInterval(timer); div.style.left?=?"-160px"; } } },?50) } </script> </head> <body> <div?id="divs"><span?id="spans">分享</span></div> <div?id="div_opacity"></div> </body> </html>
在代碼的第68行,”speed=-speed“,當onmouseleave事件觸發,div就會不停彈跳。
如果是改成”speed=-5“就不會出錯,請問這是發生了啥?蟹蟹
2016-07-01
問題出現當 觸發onmouseleave 時,傳入speed=5,而star_1 中的局部變量speed=5,由于itarget=-160<0,所以,speed=-speed,即此時局部變量speed=-5,而下一個50ms,由于itarget=-160<0不變,繼續執行speed=-speed,即此時局部變量speed=5了,到此發現問題了,在定時器的作用下,speed會在5與-5之間來回變動,有沒有達到任何 你設置的 停止條件,就出現了 無限制的抖動。而如果speed=-5,固定值 就不會出現 負負得正的情況了
2016-07-01
speed=-speed這么寫容易亂,你的目的大概是簡單的變換一下符號,第一次進這個語句speed由5變為-5,下面*3之后變為-15,當第二次執行這個語句的時候speed就會由-15變為15,這樣問題就出來了。建議你傳參數的時候參數名和局部變量名不要相同。