我的滑块代码有问题。
在这里我定义了一个函数,根据元素的数量(元素越多,滑动的次数就越多)来设置滑块的动画:
var animateSlider = function() {
var howManyTimes = Math.ceil(newContainerWidth / parentWidth)-1;
var repeatSlider = function() {
howManyTimes = Math.ceil(newContainerWidth / parentWidth)-1;
for (i=0;i<howManyTimes;i++) {
// looped code
$(".portfolio-slider").delay(2000).animate({
marginLeft: - (slideDistance * (i+1) )
}, 500);
console.log(howManyTimes);
}
$(".portfolio-slider").delay(2000).animate({
marginLeft: 0
}, 500);
}
// and this is where I set the interval for sliding:
var intervalId;
var intervalId = function() {
setInterval(repeatSlider,howManyTimes * 500);
}
intervalId();
// here's where I tried putting:
// clearInterval(intervalId)
// just to see if it clears it, but it didn't, the code interval just kept on replaying.
}如果autoplay设置为true,我将在此处启动滑块:
// fires the slider if autoplay option is set to true
if (autoplay) {
animateSlider();
}这是当我点击一个带有".filter“类的按钮时会发生的事情--它会过滤元素(在它工作时删除代码,这不是我想要关注的),然后启动animateSlider函数,这样它就可以重新计算元素的数量和它应该滑动的次数:
$('.filter').click(function(){
// it does some stuff and then animates the slider again so it recalculates the widths and number of times it's supposed to slide:
animateSlider();
});问题是,我不认为它会重新启动函数,相反,它会一次又一次地触发它,并且它不会重新计算滑块应该滑动多少次(所以当我过滤元素时,它会滑动空的幻灯片和有元素的幻灯片)。
我知道clearInterval()函数,但我尝试将它放在setInterval下,但没有成功。
理想的行为应该是-滑块滑动,在单击".filter“之后,间隔停止并以新的宽度和元素数量重新启动(而不是多次触发而不停止)。
这是我尝试处理这件事的第二天,我真的很感谢你的帮助。
发布于 2016-08-04 18:50:32
正如Will Jenkins所说,您需要返回setInterval()来获取创建的interval函数的引用。你的包装器函数实际上没有返回任何东西。你可以这样做:
var intervalId = function() {
return setInterval(repeatSlider,howManyTimes * 500);
}或
var intervalId = setInterval(repeatSlider,howManyTimes * 500);https://stackoverflow.com/questions/38764650
复制相似问题