【问题标题】:jquery, Slider only goes round oncejquery, Slider 只转一次
【发布时间】:2013-04-16 18:00:41
【问题描述】:

我有这个,这是一个图像滑块,当它到达终点并返回时,它会继续转动:

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

它本来应该继续前进,但一旦到达终点并回到第一个......它就停止了。我该如何解决这个问题?

【问题讨论】:

    标签: javascript jquery slider intervals


    【解决方案1】:

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

    【讨论】:

    • 谢谢,今天真的不行了。另外,你不会碰巧知道为什么这在 chrome 中根本不起作用? fear.kennyist.com
    • @Kennyist:WebKit 浏览器的行为与 img.width 不同,这取决于它们加载图像的方式。有一些方法可以使其正常运行,但在您的情况下,将imgWidth 设置为1000 的静态值可能更容易。这是最简单的解决方法,如果您的标题始终大小相同,它应该可以正常工作。
    • @Kennyist:我重新阅读了我的评论并意识到我不是很清楚。您的问题是由 img.width 在 Chrome 中返回 0 引起的。就像我上面说的,有解决方案,但你最好使用一个恒定的宽度值。
    猜你喜欢
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多