jquery,Slider只绕过一次

时间:2013-04-16 18:00:42

标签: javascript jquery slider intervals

我有这个,这是一个图像滑块,它意味着一旦到达结束就会继续前进:

 $(function () {
    var sliderUL = $('div.headslide').children('ul'),
    imgs = sliderUL.find('img'),
    imgWidth = imgs[0].width,
    imgsLenth = imgs.length,
    current = 1,
    totalImgsWidth = imgsLenth * imgWidth,
    direction = 'next',
    loc = imgWidth,
    interval = setInterval(swapBKgnd, 9000);

function swapBKgnd() {

    (direction === 'next') ? ++current : --current;

    if (current === 0) {
        current = imgsLenth;
        loc = totalImgsWidth - imgWidth;
        direction = 'next';
    } else if (current - 1 === imgsLenth) {
        current = 1;
        loc = 0;
    }


    transition(sliderUL, loc, direction);
};

function transition(container, loc, direction) {
    var unit;

    if (direction && loc !== 0 ) {
        unit = (direction === 'next') ? '-=' : '+=';
    }

    container.animate({
        'margin-left': unit ? (unit + loc) : loc,
    });
}
});

它意味着继续前进,但一旦它结束并回到第一个......它就会停止。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

当您到达图片的最后时,请设置loc = 0,然后设置current = 1。但是,在下一次迭代中,loc仍为0,因此它不会移动。您需要添加else

if (current === 0) {
    current = imgsLenth;
    loc = totalImgsWidth - imgWidth;
    direction = 'next';
} else if (current - 1 === imgsLenth) {
    current = 1;
    loc = 0;
} else {
    loc = imgWidth;
}

演示:http://jsfiddle.net/jtbowden/5W8Av/