為什么在滑出時會來回的晃動
<!DOCTYPE?html> <html> <head> ????<meta?charset="UTF-8"> ????<title>Document</title> ????<style?type="text/css"> ?????*{margin:0;padding:0;} ?????#div1{width:100px; ?????????height:300px; ?????????background:#98fb98; ?????????left:-100px; ?????????position:relative; ?????} ?????span{width:30px;height:100px;left:100px;background:?#0000ff;position:absolute;} ????</style> ????<script?type="text/javascript"> window.onload=function(){ ????var?timer ????var?odiv=document.getElementById('div1'); ????odiv.onmouseover=function(){ ????????startmove(10,0); ????} ????odiv.onmouseout=function(){ ????????startmove(-10,-100); ????} } function?startmove(speen,itarget){ ????var?odiv=document.getElementById('div1'); ????clearInterval(timer); ?????var?timer=setInterval(function(){ ???????? ????????if(odiv.offsetLeft==itarget){ ????????????clearInterval(timer); ????????} ????????else{ ????????????odiv.style.left=odiv.offsetLeft+speen+'px'; ????????} ????},?100) } ????</script> </head> <body> ????<div?id="div1"><span>分享</span></div> </body> </html>
不斷的加10減10 一直晃動停不下來
2015-09-03
布局有問題
2015-08-30
試了一下你這個代碼,發(fā)現(xiàn)了兩個問題:
1:滑出來時視覺上在來回的晃動。
出現(xiàn)這個問題主要是因為定時器的時間你調(diào)成100毫秒的原因,由于時間較慢,導致在視覺上有總卡殼的感覺,就是說每次調(diào)動函數(shù)的間隔時間有點大。
2:當鼠標拖離是盒子在網(wǎng)頁的邊界上不斷來回的晃動,像素大概10px。
解決方法:
window.onload=function(){
????var?timer(這個timer的定義沒有必要,因為沒辦法用到下面的函數(shù)中)}
在function?startmove(speen,itarget){}這個函數(shù)的上面定義一個全局變量,也就是var timer =null;
把
var?timer=setInterval(function(){
?????????
????????if(odiv.offsetLeft==itarget){
????????????clearInterval(timer);
????????}
????????else{
????????????odiv.style.left=odiv.offsetLeft+speen+'px';
????????}
????},?100)
這個函數(shù)中的var?timer=setInterval(function(){前面的var去掉,如果加上var就相當于重新定義了一個timer。至于為什么應該這樣我也想不通,因為這個bug有時出現(xiàn)有時不出現(xiàn)。