繁体   English   中英

在 Bootstrap 4 Carousel 单击下一步时,第一张幻灯片计数不起作用

[英]First slide count doesn't work on clicking next for Bootstrap 4 Carousel

我正在尝试获取幻灯片/总数并使其以某种方式工作。 但是,当我单击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+'');
    }
});

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

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)

您需要 else 才能最终获得正确的数字,但只需使用引导事件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM