簡體   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