javascript - 在 Javascript 中退出 setInterval

标签 javascript effects setinterval rollover

我正在尝试创建一个简单的 onmouseover 动画效果,以便当用户将鼠标悬停在 div 上时,相对定位的 div 会反弹。但是,代码不断循环,我无法弄清楚为什么 - 我是否使用 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>

如有任何建议,我们将不胜感激。

最佳答案

在设置新的间隔之前清除之前的间隔。

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

关于javascript - 在 Javascript 中退出 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7766429/

相关文章:

javascript - 我可以将多个 calendarID 与 google calendar api 一起使用吗?

javascript - 做计算时javascript可以信任吗?

jQuery UI 滑动效果问题

Swift SpriteKit 间质广告停止音效

javascript - jQuery 单击事件无法使用 setInterval 替换链接

javascript - jQuery .each() 索引值

javascript - Accordion 内容的固定按钮

javascript - JS - setInterval while 循环数组

javascript - 使用 setInterval 一个一个地打印数字,我得到 Uncaught ReferenceError