鼠标移开时清除间隔
我试图获得一个简单的图像循环(无过渡)来工作,图像在鼠标悬停时开始循环,并在鼠标移开时停止循环。除了在鼠标移出时停止之外,此方法有效。我很难弄清楚如何清除间隔:
var itemInterval = 750;
var numberOfItems = $('.portrait img').length;
//set current item
var currentItem = 0;
//show first item
$('.pimg').eq(currentItem).show();
$('.portrait').hover(function() {
//loop through the items
var infiniteLoop = setInterval(function(){
$('.pimg').eq(currentItem).hide();
if(currentItem == numberOfItems -1){
currentItem = 0;
}else{
currentItem++;
}
$('.pimg').eq(currentItem).show();
}, itemInterval);
},
function() {
clearInterval(infiniteLoop);
});
如何让倒数第二行工作?
编辑:修复了一些非代码拼写错误
I'm trying to get a simple image cycle (no transitions) to work where images begin to cycle on mouseover, and stop cycling on mouseout. This works, except for stopping on mouseout. I'm having a hard time figuring out how to clear the interval:
var itemInterval = 750;
var numberOfItems = $('.portrait img').length;
//set current item
var currentItem = 0;
//show first item
$('.pimg').eq(currentItem).show();
$('.portrait').hover(function() {
//loop through the items
var infiniteLoop = setInterval(function(){
$('.pimg').eq(currentItem).hide();
if(currentItem == numberOfItems -1){
currentItem = 0;
}else{
currentItem++;
}
$('.pimg').eq(currentItem).show();
}, itemInterval);
},
function() {
clearInterval(infiniteLoop);
});
How can I get that second-to-last line working?
Edit: fixed a couple of non-code typos
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在函数外部定义
varInfiniteLoop
,并在函数内部将超时设置为infiniteLoop = setInterval...
(不带var
)。完整代码:Define
var infiniteLoop
outside of the function, and inside the function set the timeout asinfiniteLoop = setInterval...
(withoutvar
). Full code:您在函数内声明了InfiniteLoop,该函数在您调用它的另一个匿名函数内不可用。只需在两个函数之外声明该变量即可。
you declared infiniteLoop inside a function, which is not avaiable inside the other anonimous function where you are calling it. Just declare that variable outside both functions.
我认为你有一个范围问题。尝试
I think you have a scope issue. try