使用此代码制作幻灯片动画
iam using this code to animate a slideshow
$(document).ready(function() { /* slider initiate */ var timer = setInterval(slider,5000); }); /* slider code */ var position = 0; function slider() { $('.slider .thumbs a').removeClass('selected'); position += 660; var newPosition = position * (-1) + 'px'; if (position == 1980) { position = 0; newPosition = '0px'; } var index = position / 660; $('.slider .thumbs a').eq(index).addClass('selected'); $('.slider .slider-container').animate({left: newPosition}, 1000); } /* click animation */ $('.slider .thumbs a').click(function(){ $('.slider .thumbs a').removeClass('selected'); $(this).addClass('selected'); var index = $(this).index(); var newPosition = index * (-660) +'px'; $('.slider .slider-container').animate({left: newPosition}, 1000); clearInterval(timer); var timer = setInterval(slider,5000); });但是当我点击拇指时,计时器只会加速,这意味着clearInterval不起作用 当我尝试将鼠标悬停清除它时,也会发生这种情况
but when i click on the thumbs the timer only accelerate that means that clearInterval doesn't work that happens too when i try to clear it on hover
推荐答案这是范围问题.
我想您尝试清除计时器时未定义计时器(尝试使用console.log()查看).
I guess timer is undefined when you try to clear it (try to see with console.log()).
之所以加速,是因为自clearInterval为undefined的值后,您什么都不清除,并且一次运行了2个间隔.
It accelerate because since you clearInterval on undefined value you clear nothing, and you have 2 interval running at once.
在$(document).ready范围之外定义您的第一个timer变量.
Define your first timer var outside the $(document).ready scope.
var timer; $(document).ready(function() { /* slider initiate */ timer = setInterval(slider,5000); });此外,请勿在slider函数内重新定义var timer.只需重新使用您之前声明的内容即可.
Also, don't re-define var timer inside the slider func. Just re-use the one you declared before.
但首先,请勿在slide中重复使用setInterval.您在另一个间隔内启动一个间隔.如果需要再次设置,请使用setTimeout.
But before all, don't re-use setInterval inside slide. You launch an interval within an other interval. You should use setTimeout if you need to set it again.
结论
这就足够了.使用setTimeout,您无需取消它,因为它仅触发一次.在需要时设置另一个超时,它将模拟setInterval而不需要取消它.
This is enough. With setTimeout you don't need to cancel it since it trigger only once. Set another timeout while you need to and it will simulate a setInterval without the need of canceling it.
$(document).ready(function() { /* slider initiate */ setTimeout(slider,5000); }); function slider() { // your code setTimeout(slider, 5000); }更多推荐
清除间隔不起作用
发布评论