2011-10-14 39 views
0

我試圖創建一個簡單的onmouseover動畫效果,以便當用戶鼠標移過div時,相對位置的div會彈跳。然而,代碼保持循環,我不能解決原因 - 我是否嚴重使用setInterval()?這裏是:在Javascript中退出setInterval

<html> 
<head> 
<title>Bouncer Test Page</title> 

<style rel="stylesheet" type="text/css"> 
div#container{ 
background-color: #ffffff; 
width:200px; 
height: 100px; 
text-align:center; 
} 

div#bouncer{ 
position:relative; 
top:50px; 
} 

</style> 
</head> 
<body> 
<div id="container"> 
<div id="bouncer"> 
<img src="button.jpg"/> 
</div> 
<!-- end of the #bouncer div --> 
</div> 
<!-- end of the #container div --> 
<script> 


var selDiv = document.getElementById("bouncer"); 
var containerDiv = document.getElementById("container"); 
var index = 10; 
var intervalHandle1; 


function popImage(){ 
selDiv.style.top = relativeHeights[index]; 
index--;  
     if(selDiv.style.top === '0px'){ 
     index = 0; 
     window.clearInterval(intervalHandle1); 
     dropImage(index, intervalHandle1); 
     } 
} 


window.onload = function(){ 
relativeHeights = ['0px', '5px', '10px', '15px', '20px', '25px', '30px', '35px', '40px', '45px', '50px']; 
containerDiv.onmouseover = function(){ 
intervalHandle1 = setInterval(popImage, 50); 
} 

} 
// end of the window.onload anonymous function 

function dropImage(){ 
console.log("dropImage was called with index of " + index + ". intervalHandle1 was set to " + intervalHandle1 

// insert dropImage code here 
); 
} 


</script> 
</body> 
</html> 

任何建議將不勝感激。

回答

4

清除之前的間隔,然後再設置一個新的間隔。

containerDiv.onmouseover = function(){ 
    clearInterval(intervalHandle1); 
    intervalHandle1 = setInterval(popImage, 50); 
} 
+0

感謝羅布,它像一個魅力工作。 – Sceletia