How to output current slide number in Bootstrap 3 Carousel?

白昼怎懂夜的黑 提交于 2019-12-21 16:53:58

问题


I'm looking to output the current slide number using Bootstrap 3's Carousel plugin. Ideally, I would like to have this as text underneath the carousel div. For example:

[CAROUSEL HERE]
3 of 9

I can output the total number of images (e.g. 9 in the example above) using a function in my CMS, but I can't figure out how to get the active slide (e.g. 3 in the example above.)

I have searched all over and found one thread that seemed to do just that: How to Get total and Current Slide Number of Carousel

Unfortunately, I think the solution in the above thread doesn't work in Bootstrap version 3. Or maybe I'm just messing something up.

Does anyone know if this is possible? I'm really hoping it is! Any help or suggestions would be greatly appreciated. Thanks!


回答1:


You can use the .getActiveIndex() method of the bootstrap plugin (I don't think it works in bootstrap 2 though).

// Listen to the 'slid carousel' event
// to trigger our code after each slide change
$('.carousel').on('slid.bs.carousel', function () {

  // This variable contains all kinds of data and methods related to the carousel
  var carouselData = $(this).data('bs.carousel');
  // EDIT: Doesn't work in Boostrap >= 3.2
  //var currentIndex = carouselData.getActiveIndex();
  var currentIndex = carouselData.getItemIndex(carouselData.$element.find('.item.active'));
  var total = carouselData.$items.length;

  // Create the text we want to display.
  // We increment the index because humans don't count like machines
  var text = (currentIndex + 1) + " of " + total;

  // You have to create a HTML element <div id="carousel-index"></div>
  // under your carousel to make this work
  $('#carousel-index').text(text);
});


Working demo here: http://jsfiddle.net/nUgy4/2/ , I hope you will find it useful.



来源:https://stackoverflow.com/questions/19921627/how-to-output-current-slide-number-in-bootstrap-3-carousel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!