如何获取轮播的总数和当前幻灯片数量
你能告诉我如何获得引导程序中旋转木马滑块的总数和当前数量,如下图所示吗?
我有一个标准的Bootstrap轮播和一个带有.num
类的
来显示总数和当前数,我使用这段代码来检索数字,但它没有通过
$('.num').html(){ $('#myCarousel').carousel({number}) }
谢谢
更新:
请在这个jsfiddle LINK上找到一个样本
每张slide
都有一个.item
类,你可以得到像这样的幻灯片总数
var totalItems = $('.item').length;
活动slide
有一个名为active
的类,你可以像这样得到active slide
的索引
var currentIndex = $('div.active').index() + 1;
您可以通过绑定像这样的bootstrap carousel slid
事件来更新这些值
$('#myCarousel').bind('slid', function() { currentIndex = $('div.active').index() + 1; $('.num').html(''+currentIndex+'/'+totalItems+''); });
例
更新了@Khawer Zeshan的代码
对于Bootstrap 3.0+,使用slid.bs.carousel
而不是slid.bs.carousel
和on
而不是bind
。 所以更新代码就是这样的
var totalItems = $('.item').length; var currentIndex = $('div.active').index() + 1; $('#myCarousel').on('slid.bs.carousel', function() { currentIndex = $('div.active').index() + 1; $('.num').html(''+currentIndex+'/'+totalItems+''); });
var totalItemsPop = $('#Mycarousel .item').length; $('#Mycarousel').on('slide.bs.carousel', function() { setTimeout(function(){ currentIndexPop = $('#Mycarousel div.active').index() + 1; $('.num').html('' + currentIndexPop + '/' + totalItemsPop + ''); }, 1000); });
在幻灯片事件div激活后无法获取活动索引,因此请将代码保留在设置超时function中
Bootstrap 3.2+:
carouselData.getItemIndex(carouselData.$element.find('.item.active'))
您可以使用jquery index()函数获取项目列表中活动元素的当前索引。 所以代码看起来像这样:
var currentItem = $("#carousel-1 .item.active" ); var currentIndex = $('#carousel-1 .item').index(currentItem) + 1;
以下代码的唯一缺点是,在您转到下一张幻灯片之前它不会显示(每次幻灯片更改后触发)。
JS / jQuery的
$('#carousel-slide').on('slid.bs.carousel', function () { var carouselData = $(this).data('bs.carousel'); var currentIndex = carouselData.getActiveIndex(); var total = carouselData.$items.length; var text = (currentIndex + 1) + " of " + total; $('#carousel-index').text(text); });
HTML