Twitter Bootstrap Carousel autoplay on load

2020-05-31 07:37发布

问题:

Using the twitter bootstrap framework, how is it possible to invoke the carousel to 'auto slide.' Meaning when the page loads, the carousel automatically scrolls.

I have tried a javascript onLoad click function for the <a> of the next link, but this didn't work.

回答1:

you should do as the Twitter Bootstrap Documentation says about Carousel, so set the first Carousel slide item with class="active" and initialize the js for the carousel in this way:

$(function(){
    $('.carousel').carousel({
      interval: 2000
    });
});

then if it's not enough (but this never happened to me) use the bruteforce triggering the click hover the carousel control buttons like this:

$(function(){
$('.carousel').carousel({
      interval: 2000
    });
$('.carousel-control.right').trigger('click');
});

but this is just a not-needed trick, really, just follow the documentantion!



回答2:

Simple. You're missing the "data-ride" attribute in the div.

<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">



回答3:

As per the docs, you need to initialize the Carousel plugin via JavaScript. The carousel example on the official Bootstrap documentation page is initialized in the application.js file on lines 67-68:

// carousel demo
$('#myCarousel').carousel()

which gives it the default settings.

If you want to specify the cycle interval, you can set the interval property in milliseconds:

$('.carousel').carousel({
  interval: 2000
})


回答4:

Put it in the document-ready-block make it auto-start for me

$(document).ready(function() {
$('#myCarousel').carousel();
});


回答5:

<div id="myCarousel" class="carousel slide" data-ride="carousel"> works for me, what I have been missing was the data-ride attribute.

I hope this will help a lot of people. Thank you stackoverflow, you have been very useful to me on most grounds. Am glad this community exists.



回答6:

You can use the data-interval attribute on the html markup to auto play:

<div id="carousel-example-generic" class="carousel slide" data-ride="carousel"  data-interval="5000">

data-interval: The amount of time in milliseconds to delay between automatically cycling an item. If false, carousel will not automatically cycle.



回答7:

<header id="myCarousel" class="carousel slide">

YOU NEED ADD

data-ride="carousel"

<header id="myCarousel" class="carousel slide" data-ride="carousel">


回答8:

Just add data-interval="5000" to the div with the IP carouselExampleIndicators.

Like this:

<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel" data-interval="5000">


回答9:

For Bootstrap 4 and onwards:

$(function(){
    $('.carousel').carousel({
      interval: 2000,
      ride: 'carousel' // this is the important part
    });
});


回答10:

Simply add the class "slide" to the carousel div tag, like this:

<div class="carousel slide" id="this-carousel-id">