Bootstrap 4 data-slide-to not working

2019-08-21 17:24发布

问题:

According to Bootstrap's documentation, I should be able to target a specific slide in a carousel and go to that slide with the data-slide-to attribute. I've fixed up a quick example here: https://codepen.io/alemieux/pen/mqzVML

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-slide-to="0">
Go to First Slide
</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-slide-to="1">
Go to Second Slide
</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-slide-to="2">
Go to Third Slide
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModal" aria-hidden="true">
   <div class="modal-dialog" role="document">
      <div class="modal-body">
         <!-- Carousel with controls -->
         <div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
            <div class="carousel-inner">
               <div class="carousel-item active">
                  <h1>This is the first slide</h1>
                  <p>The content of slide 1</p>
               </div>
               <div class="carousel-item">
                  <h1>This is the Second slide</h1>
                  <p>The content of slide 2</p>
               </div>
               <div class="carousel-item">
                  <h1>This is the Third slide</h1>
                  <p>The content of slide 3</p>
               </div>
               <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
               <span class="carousel-control-prev-icon" aria-hidden="true"><i class="fa fa-chevron-left" aria-hidden="true"></i></span>
               </a>
               <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
               <span class="carousel-control-next-icon" aria-hidden="true"><i class="fa fa-chevron-right" aria-hidden="true"></i></span>
               </a>
            </div>
         </div>
         <!-- End Carousel -->
      </div>
      <button type="bottom" class="btn btn-secondary" data-dismiss="modal">Close</button>
   </div>
</div>

But it's not working. The carousel is inside a modal and I'm wondering if that's the issue.

回答1:

I think that the data-slide-to attribute was designed to be used on <ol> items inside the main carousel tag. However, with a little javascript you can make it work:

$('button[data-slide-to]').on('click', function(){
    $('#carouselExampleControls').carousel($(this).data('slide-to'));
});

Also, I would consider to set data-interval="false" on the carousel tag in order to stop the automatic cycling.

UPDATE: CodePen



标签: bootstrap-4