开发者

If statement in setInterval only working once

I'm new to Stack Overflow, so excuse me if I'm completely doing something I shouldn't be doing, and let me know so I can learn.

Anyway! The code:

$(document).ready(function() {    
    var imgWidth = $(".window").width();
    var imgSize = $(".image_reel img").size();
    var imgReelWidth = imgWidth * imgSize;


    $(".image_reel").css({
        width: imgReelWidth});

    var num = 960;
    var numImgs = $('div.image_reel img').length;
    var currentSlide = 0;

    setInterval(function() {    
        currentSlide++;

        if (currentSlide != numImgs) {
            $(".image_reel").animate({
                left: -num
            }, 1000);
        }
        else {
            var setWidth = numImgs - 1;
            var newSlideNum = num * setWidth;
            $(".image_reel").animate({
                left: newSlideNum
            }, 1000);
            currentSlide = 0;    
        }
    }, 2000);
});

What this code is supposed to be doing (or at least I thought it was...) is that after 2 seconds, it will loop through the if statement and check if the "current slide" is equal to the amount of images there are. Now I checked with the alert function to see if all the numbers are correct and they are, but for some reason, the slider is only working once, and that's it. Any ideas why?

T开发者_JS百科hanks in advance guys.


This might be your problem:

var numImgs = $('div.image_reel img').length;

This holds the number of images at the moment it's called, not every time you call it. Replace numImgs with $('div.image_reel img').length in your code, and see if it works:

$(document).ready(function() {
    var imgWidth = $(".window").width();
    var imgSize = $(".image_reel img").size();

    $(".image_reel").css('width', imgWidth * imgSize);

    var num = 960;
    var currentSlide = 0;
    var setWidth = 0;
    var newSlideNum = 0;

    setInterval(function() {
        currentSlide++;

        if (currentSlide < $('div.image_reel img').length) {
          $(".image_reel").animate({left: -num}, 1000);
        } else {
            setWidth = numImgs - 1;
            newSlideNum = num * setWidth;
            $(".image_reel").animate({left: newSlideNum}, 1000);
            currentSlide = 0;
        }
    }, 2000);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜