我想在JavaScript中启用自动滑块和无限循环

时间:2013-03-02 09:01:14

标签: javascript jquery html slider

<script type="text/javascript">
$(document).ready(function() {

var acch = 1;
$('.controls ul a').click(function() {
    var chno = $('.slider-container li').length;
    switch($(this).attr('data-gallery')){
        case 'slide-left': 
            if (acch < chno){
                acch++;
                startSlide(acch);
            }       
        break;
        case 'slide-right':
            if (acch <= 1){
                acch = 1;   
            }else{
                acch--;
                startSlide(acch);
            }
        break;  
    }
})

function startSlide(itemNo){
    var sTo = '#slider-item-' + itemNo;
    $('#home-top-content').scrollTo($(sTo), 300);   
}

$('.backToTop').click(function() {
     $('html, body').animate({scrollTop:0}, 'slow');
})

})
</script>

这是上面列出的脚本我需要启用自动滑动功能和无限循环 http://aphex.fresh-pixel.com/ 这是我正在使用的主题的链接,你可以在滑块

中看到问题

1 个答案:

答案 0 :(得分:0)

我认为这种实现方式更好,因为您可以在设计中添加任意数量的幻灯片而不会在代码中出现任何问题。

<script type="text/javascript">
$(document).ready(function() {

    $('.controls ul a').click(function() {
        moveSliders($(this));
    })

    function startSlide(element){
        $('#home-top-content').scrollTo(element, 300);   
    }

    $('.backToTop').click(function() {
         $('html, body').animate({scrollTop:0}, 'slow');
    })

    setInterval(function(){
        moveSliders($('.controls ul').find('a.arrow-right'));
        },6000);

    function moveSliders(clickElement)
    {
        //Get li with class active if that count is zero put it as the first li
        var currentActive = $('.slider-container li.slide-active');
        var firstElement = $('.slider-container li:first');
        var lastElement = $('.slider-container li:last');
        if(currentActive.length == 0){
            firstElement.addClass('slide-active');
            currentActive = firstElement;
        }

        switch(clickElement.attr('data-gallery')){
            case 'slide-left': 
                //Next
                var nextElement = currentActive.next();
                if(nextElement.length == 0)nextElement = firstElement;
                $('.slider-container li.slide-active').removeClass('slide-active');
                nextElement.addClass('slide-active');
                startSlide(nextElement);
            break;
            case 'slide-right':
                //previous
                var previousElement = $('.slider-container li.slide-active').prev();
                if(previousElement.length == 0)previousElement = lastElement;
                $('.slider-container li.slide-active').removeClass('slide-active');
                previousElement.addClass('slide-active');
                startSlide(previousElement);
            break;  
        }
    }

})
</script>