Slider只循环一次

jquery, Slider only goes round once

本文关键字:一次 循环 Slider      更新时间:2023-09-26

我有这个,这是一个图像滑动条,它意味着在它到达结束和返回时继续旋转:

 $(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,
    });
}
});

它意味着继续,但一旦它到达最后,回到第一个…它停止。我该如何解决这个问题?

当您到达图像的末尾时,您设置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/