質問

I'm using Twitter Bootstrap's carousel script to make a logo showoff carousel. The logos should be randomly ordered, shuffling each time the user refreshes the page

I have searched a lot on Google found some solutions but none of them worked for me, I don't know what can be happening... Anyway:

Here's the fiddle: http://jsfiddle.net/HGWMy/1/

<div id="carousel-example-generic" 
     class="carousel slide" 
     data-ride="carousel" 
     style="width: 180px; margin: 0 auto">

    <!-- Wrapper for slides -->
    <div class="carousel-inner">
        <div class="item active">
            <a href="#"><img src="http://i.imgur.com/jSfZIJK.png" alt="Vale"></a>
        </div>
        <div class="item">
            <a href="#"><img src="http://i.imgur.com/z2FyBAt.png" alt="Petrobras"></a>
        </div>
        <div class="item">
            <a href="#"><img src="http://i.imgur.com/mZtv0bA.png" alt="IGAM"></a>
        </div>
        <div class="item">
            <a href="#"><img src="http://i.imgur.com/tqgQxbq.png" alt="Arcelor Mittal"></a>
        </div>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
  $('.carousel').carousel({
    interval: 1000
  })
});
</script>
役に立ちましたか?

解決

You can shuffle an array of images and build the divs before loading the carousel...

<div id="carousel-example-generic" class="carousel slide" data-ride="carousel" style="width: 180px; margin: 0 auto">
    <!-- Wrapper for slides -->
    <div class="carousel-inner"></div>
</div>

jQuery(document).ready(function ($) {
    var images = [{
        url: "http://i.imgur.com/jSfZIJK.png",
        alt: "Vale"
    }, {
        url: "http://i.imgur.com/z2FyBAt.png",
        alt: "Petrobras"
    }, {
        url: "http://i.imgur.com/mZtv0bA.png",
        alt: "IGAM"
    }, {
        url: "http://i.imgur.com/tqgQxbq.png",
        alt: "Arcelor Mittal"
    }];

    // http://css-tricks.com/snippets/javascript/shuffle-array/
    images.sort(function () { return 0.5 - Math.random(); });

    $.each(images, function (index, image) {

        var element = $('<div class="item"><a href="#"><img src="' + image.url + '" alt="' + image.alt + '" /></a></div>')

        if (index === 0) {
            element.addClass("active");   
        }

        element.appendTo("div.carousel-inner");
    });

    $('.carousel').carousel({
      interval: 1000,
    })
});

fiddle: http://jsfiddle.net/HGWMy/5/

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top