停止javascript无限循环onmouseout
Stop javascript infinite loop onmouseout?
我正在"动画"一个悬浮的精灵。问题是我不知道如何在mouseout上停止循环。所以基本上在鼠标悬停之后,精灵会无限移动。
$("#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;
});
我如何使它停止在mouseout?还有,是否有最短(更少的代码)的版本来做同样的事情?在我的印象中,我在循环中浪费了很多行。由于
我尝试了这个基于Pointy注释,但不知道如何正确地做:
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);
});
试试这个
$("#explore").hover(function () { // Listen for hover
var number2 = 0;
$(this).data("hovertimer", 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 () {
clearTimeout($(this).data("hovertimer"));
sprite2.style.marginLeft=0;
});
当您调用"setInterval()"时,将它返回的值保存在某个变量中(或在".data()"属性中)。然后,当你想要停止动画时,将该值传递给"clearInterval()"。
var timer = setInterval(function() { ...
// later ...
clearInterval(timer);
我知道这是一个旧的帖子,但有一个轻量级的插件(我碰巧是开发人员),它被称为"spriteOnHover jQuery plugin",它的工作为动画精灵悬停和鼠标事件,并有参数做几乎所有的技巧。当然它是开源的。jQuery spriteOnHover
相关文章:
- 使用滚动溢出-x进行无限循环
- 从index.html调用函数,该函数无限循环
- 使用jQuery无限循环播放HTML页面幻灯片
- Grunt任务没有加载,获得无限循环
- 如何在不进入无限循环的情况下将网站重定向到Facebook画布URL
- Backbone+RequireJS+Mediator模式导致视图逻辑短路和无限循环
- jQuery无限循环,动画化许多项目
- 如何避免试图用php+jquery显示php起始页的无限循环
- 6502仿真增强型基本无限循环$C000至$E0ED
- Angular ngRoute导致无限循环和堆栈溢出
- Jquery:无限循环和暂停
- 数组数组:无限循环
- MeteorJS使用流星调用和流星方法时的无限循环
- 如何无限循环数据集字符串
- jquery在无限循环中运行
- 遍历对象会导致无限循环
- 为什么内部Javascript循环会阻止外部循环中断(即无限循环)
- 角度编译指令似乎进入了无限循环
- 显示随机数js的无限循环
- 停止javascript无限循环onmouseout