0

Currently I'm using this jquery code that I got from another post here to fade some divs in and out

<script>
$(document).ready(function () {
    var divs = $('div[id^="feature-"]').hide(),
        i = 0;
    (function cycle() {
        divs.eq(i).fadeIn(400)
            .delay(5000)
            .fadeOut(400, cycle);
        i = ++i % divs.length;
    })();
});    
</script>

to cycle through some divs, to make them fade in and fade out in a sort of haphazard slideshow. I would like to randomize the displayed order on page load, for example right now it shows feature-1, then feature-2, then feature-3. How can I get it to randomize that order, like sometimes onload will show feature-3, feature-1, feature-2, and sometimes it will show feature-2, feature-1, feature-3, etc etc. I tried creating an array and then randomizing numbers between 1 and 10 and placing them in indices 0-9, but I couldn't get it to display at all after I tried. Here's a jfiddle to show what it's doing.

http://jsfiddle.net/gthes/

4

2 回答 2

1

利用Math.Random()

http://www.w3schools.com/jsref/jsref_random.asp

示例:从 1 到 6 的随机数

$(document).ready(function () {
    var divs = $('div[id^="feature-"]').hide(),
        i = 0,
        lastIndex=-1;
    (function cycle() {
         do{     
            i = Math.floor((Math.random()*6));       
         }while(i==lastIndex);

        divs.eq(i).fadeIn(400)
            .delay(5000)
            .fadeOut(400, cycle);      

         lastIndex=i;

    })();
}); 
于 2013-05-22T16:52:00.453 回答
1
$(document).ready(function () {
    var divs = $('div[id^="feature-"]').hide(), last_index = false;

    function get_random_index(max) {
        return Math.floor(Math.random() * max);
    }

    function cycle() {
        var i;
        do {
            i = get_random_index(divs.length);
        } while (i === last_index);
        last_index = i;     
        divs.eq(i).fadeIn(400).delay(5000).fadeOut(400, cycle);
    }
    cycle();
}); 
于 2013-05-22T16:52:14.273 回答