我在悬停时将一个精灵“动画化”。问题是,我不知道如何停止循环onmouseout。所以基本上在鼠标悬停后,精灵会无限期地移动。停止javascript无限循环onmouseout?
$("#explore").hover(function() { // Listen for hover
var number2 = 0;
setInterval(function() { // Animate sprite changing it's margin
switch (number2) {
case 0:
sprite2.style.marginLeft=-32;
number2++;
break;
case 1:
sprite2.style.marginLeft=-64;
number2++;
break;
case 2:
sprite2.style.marginLeft=0;
number2 = 0;
}
}, 120);
},function() {
sprite2.style.marginLeft=0;
});
如何让它停止onmouseout?还有一个最短的代码版本可以做同样的事情吗?我的印象是我在循环中浪费了很多线条。由于
我试过此基础上尖尖的评论,但无法弄清楚如何正确地做到这一点:
var number2 = 0;
var timer = setInterval(function() {
switch (number2) {
case 0:
sprite2.style.marginLeft=-32;
number2++;
break;
case 1:
sprite2.style.marginLeft=-64;
number2++;
break;
case 2:
sprite2.style.marginLeft=0;
number2 = 0;
}
}, 120);
},function() {
clearInterval(timer);
});
关于您的更新,您需要声明'var timer' _outside_该函数,以便mousein和mouseout函数都可以访问该函数。 – nnnnnn