单击Bootstrap 4 Carousel的下一个按钮时,第一个幻灯片计数不起作用

时间:2019-09-21 12:11:55

标签: javascript jquery css twitter-bootstrap bootstrap-4

我正在尝试获取幻灯片/总数,并使其以某种方式工作。但是,当我单击next并返回到原始的第一张幻灯片时,它没有显示1/4,但仍然是4/4

JSFiddel:https://jsfiddle.net/zorw7yLe/

HTML:

<div class="num"></div>
<a class="next" href="#carouselExampleIndicators" role="button" data-slide="next"> -->>></a>
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner">
    <div class="carousel-item item active">
      <img class="d-block w-100" src="https://via.placeholder.com/500x300" alt="First slide">
      <div class="carousel-caption">
        <h5>Title of the first image</h5>
        <p>Some description of the first image</p>
      </div>
    </div>
    <div class="carousel-item item">
      <img class="d-block w-100" src="https://via.placeholder.com/500x300" alt="Second slide">
      <div class="carousel-caption">
        <h5>Title of the second image</h5>
        <p>Some description for the second image</p>
      </div>
    </div>
    <div class="carousel-item item">
      <img class="d-block w-100" src="https://via.placeholder.com/500x300" alt="Third slide">
      <div class="carousel-caption">
        <h5>Title of the third image</h5>
        <p>Some description for the third image</p>
      </div>
    </div>
    <div class="carousel-item item">
      <img class="d-block w-100" src="https://via.placeholder.com/500x300" alt="Fourth slide">
      <div class="carousel-caption">
        <h5>Title of the fourth image</h5>
        <p>Some description for the fourth image</p>
      </div>
    </div>
  </div>
</div>

JS:

var totalItems = $('.carousel-item').length;
var currentIndex = $('.carousel-item.active').index() + 1;
var down_index;
$('.num').html(''+currentIndex+'/'+totalItems+'');

    $(".next").click(function(){
    currentIndex_active = $('.carousel-item.active').index() + 2;
    if (totalItems >= currentIndex_active)
    {
        down_index= $('.carousel-item.active').index() + 2;
        $('.num').html(''+currentIndex_active+'/'+totalItems+'');
    }
});

1 个答案:

答案 0 :(得分:2)

我建议您使用引导轮播事件,不需要直接在链接上观看点击:

https://getbootstrap.com/docs/4.0/components/carousel/#events

var totalItems = $('.carousel-item').length; 

$('#carouselExampleIndicators').on('slide.bs.carousel', function (e) {
    $('.num').html((e.to+1)+'/'+totalItems);
});

因此您的计数器将跟踪当前幻灯片

此外,由于您的状况(totalItems> = currentIndex_active),您的计数器不会返回到1/4,在最后一张幻灯片上,如果您在索引上添加+2,则为5,高于totalItems(4 )

您最终需要获得其他号码才能获得正确的号码,但只需使用引导事件即可