如何使这个“滑块”javascript无限旋转图像?

时间:2012-03-30 14:40:50

标签: javascript image rotation

我正在尝试帮助一个朋友,他的主页上有一个旋转窗格,图片不会在无限循环上滚动。它们滚动然后回滚到开头并重新开始。

以下是他提供的Javascript代码段:

$(function () {
    if ($('#customScroller').length != 0) { //check if we're on the right page
        var width = $('#slider a').length;
        $('#slider').width(width * 930); //give the slider the appropriate width
        var count = 0;
        initial slide position

        function slide() {
            if (count < (width - 1)) { //we want to check if at end of the slider
                count++;
            }
            else {
                count = 0;
            }
            var toMove = 0;
            toMove = (-1 * (count * 930));
            $('#slider').animate({
                left: toMove
            }, 1000, function () {
                //complete
            });
        }
        var s = window.setInterval(slide, 8500);
    }
});

将它转换为无限循环是多少工作?

编辑:这是网站:http://www.ralphshardwood.com

1 个答案:

答案 0 :(得分:2)

你会想要以不同方式评价这一点。为了达到理想的效果,您需要将幻灯片从容器的右边缘绝对放置,并从左侧动画下一个幻灯片,确保它具有更高的z-index(而不是移动整个列表,这是维护你的订单。

您可以获得下面的要点,并将其纳入您现有的标记中。这是一个有效的jsFiddle:http://jsfiddle.net/rgthree/mGeqx/

if ($('#slides').length != 0) {
    var currentIndex = 0, slides = $('#slides > li');
    $(slides[currentIndex]).css('left','0%');
    function slide() {
        var current, next;
        current = $(slides[currentIndex]);
        currentIndex++;
        if(currentIndex === slides.length){
          currentIndex = 0;   
        }
        next = $(slides[currentIndex]);
        next.css('left','100%');
        next.css('z-index',parseInt(current.css('z-index'), 10)+1);
        next.animate({left: '0%'}, 1000);
    }
    var s = window.setInterval(slide, 2000);
}

标记:

<ul id="slides">
    <li>Slide1</li>
    <li>Slide2</li>
    <li>Slide3</li>
    <li>Slide4</li>
    <li>Slide5</li>
</ul>​

CSS:

ul#slides {position:relative; width:400px; height:200px; overflow:hidden;}
ul#slides > li {
    position:absolute;
    top:0px;
    left:100%;
    width:100%;
    height:100%;
    background:#777;
    color:#FFF;
    z-index:1;
}

ul#slides > li:nth-child(even) {background:#444;}

相关问题