1

我使用 jQuery 创建了一个轮播,我想为其添加自动播放功能。

这是我现有的 JS:

$(document).ready(function (){
    $('#button a').click(function(){
        var integer = $(this).attr('rel');
        $('#myslide .cover').animate({left:-705*(parseInt(integer)-1)})
        $('#button a').each(function(){
            $(this).removeClass('active');
            if($(this).hasClass('button'+integer)){
                $(this).addClass('active')}
        });
    });
});​

这是一个工作小提琴

问:我不知道从哪里开始自动播放。有什么建议么?

4

4 回答 4

2

看一下这个:

http://jsfiddle.net/gy7LE/13/

$(document).ready(function (){

    $('#button a').click(function(){
        var integer = $(this).attr('rel');
        $('#myslide .cover').animate({left:-705*(parseInt(integer)-1)})
        $('#button a').each(function(){
            $(this).removeClass('active');
            if($(this).hasClass('button'+integer)){
                $(this).addClass('active')}
        });
    });
        setInterval ( function(){Next();}, 1000 );
    });

    function Next(){
        var _next = false;
        $('#button a').each(function(){
            if(_next){
                $(this).addClass('active');
                _next = false;
            }
            else if($(this).hasClass('active')){
                _next = true;
                $(this).removeClass('active')
            }

        });  
        if(_next)
            $("#button a:eq(0)").addClass("active");

       var activeIndex = parseInt($(".active").attr("rel"));
       $('#myslide .cover').animate({left:-705*(parseInt(activeIndex))});      
    }
​
于 2012-04-13T14:50:19.620 回答
1

这将起作用。查看代码中的注释:

var slideInterval = null;

$(document).ready(function() {
    $('#button a').click(function() {
        //Clear slide interval to allow overriding of auto slide
        if (slideInterval !== null) clearInterval(slideInterval);

        var integer = $(this).attr('rel');
        DoSlide(integer);
    });

    //Begin auto slide
    slideInterval = setInterval(DoSlide , 2000);
});

function DoSlide(integer) {
    integer = integer || parseInt($('.active').attr('rel')) + 1;

    // Reset auto slide
    if (integer == 5) integer = 1;

    $('#myslide .cover').animate({
        left: -705 * (parseInt(integer) - 1)
    });

    $('.active').removeClass('active');    
    $('a[rel="' + integer + '"]').addClass('active');
}​

这是一个要演示的工作小提琴

于 2012-04-13T14:53:17.623 回答
1

更优雅的解决方案

$(document).ready(function() {
  setTimeout(function () {
    $('.carousel-control.right').trigger('click');
    $('.carousel-inner').trigger('mouseenter');
    $('.carousel-inner').trigger('mouseleave');
  }, 3000); //set this time to what ever time you want it to take to start scrolling this is separate for the interval you set for the carousel though you can set it to be the same BooStrap default is 4000
});
于 2013-04-24T05:21:53.387 回答
0

你可以试试这个插件,它会为你寻找图像并创建自动轮播。

于 2015-03-04T20:58:52.683 回答