Twitter Bootstrap Carousel slide duration

前端 未结 4 1307
别跟我提以往
别跟我提以往 2020-12-19 15:50

In the Twitter Bootstrap Carousel, how can I make a particular slide to have a different duration than others?

I can change the whole slider duration with the \"inte

4条回答
  •  被撕碎了的回忆
    2020-12-19 16:46

    Bootstrap 3.1 carousel don't allow diferent duration for each slide, but it offers one method and one event that we can use in order to ahieve this.

    We will use the slid.bs.carousel event to detect when the carousel has completed its slide transition and the .carousel('pause') option to stop the carousel from cycling through items.

    We will use this attribute data-interval="x" on each carousel item with different time duration, so our html will look like this for example:

    
    

    Now, all we have to do is to:

    1. detect when a new item is displayed using the slid.bs.carousel event
    2. check his duration
    3. pause the carousel using .carousel('pause')
    4. set a timeout with the duration of the item and after the duration completed we should unpause the carousel

    The javascript code will look like this:

    var t;
    
    var start = $('#myCarousel').find('.active').attr('data-interval');
    t = setTimeout("$('#myCarousel').carousel({interval: 1000});", start-1000);
    
    $('#myCarousel').on('slid.bs.carousel', function () {   
         clearTimeout(t);  
         var duration = $(this).find('.active').attr('data-interval');
    
         $('#myCarousel').carousel('pause');
         t = setTimeout("$('#myCarousel').carousel();", duration-1000);
    })
    
    $('.carousel-control.right').on('click', function(){
        clearTimeout(t);   
    });
    
    $('.carousel-control.left').on('click', function(){
        clearTimeout(t);   
    });
    

    As you can see, we are forced at the begining to add a starting interval and i've set it to 1000ms but i remove it each time i pause the carousel duration-1000. I've used the lines below to resolve the first item problem because that item was not caught by the slid event.

    var start = $('#myCarousel').find('.active').attr('data-interval');
    t = setTimeout("$('#myCarousel').carousel({interval: 1000});", start-1000);
    

    I also noticed that if the user presses the arrows, the timeout is going crazy, that's why i clear the timeout each time the user press on the left and right arrow.

    Here is my live example http://jsfiddle.net/paulalexandru/52KBT/, hope this response was helpful for you.

提交回复
热议问题