Twitter Bootstrap Carousel - access current index

后端 未结 9 1227
面向向阳花
面向向阳花 2020-12-02 14:11

How do I get the current index from the carousel?

In this case I am using an unordered list. I know I could search through the list items to find the one with the \'

相关标签:
9条回答
  • 2020-12-02 14:51

    Instead of adding and subtracting from the current slide, try this on the 'slide' event:

    $('.carousel').on('slide',function(e){
        var slideFrom = $(this).find('.active').index();
        var slideTo = $(e.relatedTarget).index();
        console.log(slideFrom+' => '+slideTo);
    });
    
    0 讨论(0)
  • 2020-12-02 14:51

    For bootstrap 3 it's

    $('#myCarousel').on('slide.bs.carousel', function (e) {
      var active = $(e.target).find('.carousel-inner > .item.active');
      var from = active.index();
      var next = $(e.relatedTarget);
      var to = next.index();
      console.log(from + ' => ' + to);
    })
    

    from https://github.com/twbs/bootstrap/pull/2404#issuecomment-22362366

    0 讨论(0)
  • 2020-12-02 14:53

    Nope, there is no way to access index or direction.

    See here

    // EDIT

    Bootstrap changed repos, new link

    0 讨论(0)
  • 2020-12-02 14:53

    This worked for me (Bootstrap 3)

    $("#myCarousel").on('slide.bs.carousel', function(evt) {
      console.debug("slide transition started")
      console.debug('current slide = ', $(this).find('.active').index())
      console.debug('next slide = ', $(evt.relatedTarget).index())
    })
    
    0 讨论(0)
  • 2020-12-02 14:58

    I'm doing it like that, that works sort of very well ;)

    var slider = $("#slider-wrapper")
        .carousel({
            interval: 4000
        })
        .bind('slid', function() {
            var index = $(this).find(".active").index();
            $(this).find("a").removeClass('pager-active').eq(index).addClass('pager-active');
        });
    
    $("#slider-wrapper a").click(function(e){
        var index = $(this).index();
        slider.carousel(index);
        e.preventDefault();
    });
    
    0 讨论(0)
  • 2020-12-02 14:59

    It appears Bootstrap 4 finally has the native implementation of this.

    https://github.com/twbs/bootstrap/pull/21668

    $('#myCarousel').on('slide.bs.carousel', function(e){
      e.direction     // The direction in which the carousel is sliding (either "left" or "right").
      e.relatedTarget // The DOM element that is being slid into place as the active item.
      e.from          // The index of the current item.     
      e.to            // The index of the next item.
    });
    
    0 讨论(0)
提交回复
热议问题