Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

javascript - jquery move elements into a random order

I am attempting to display a series of images in a random order. However, I do not want any single item to repeat until all items have been shown, so instead of selecting a random image from the array, I want to take the entire array, randomize it, and then select in sequence from the first to the last element. Here's my code:

HTML:

<div id="tout4"
<img src="images/gallery01.jpg" class="img_lg"/>
<img src="images/gallery02.jpg" class="img_lg"/>
<img src="images/gallery03.jpg" class="img_lg"/>
</div>

and the javascript, which currently selects and displays the items in order:

var galleryLength = $('#tout4 img.img_lg').length;
var currentGallery = 0;
setInterval(cycleGallery, 5000);


function cycleGallery(){

    $('#tout4 img.img_lg').eq(currentGallery).fadeOut(300);

    if (currentGallery < (galleryLength-1)){
        currentGallery++;
    } else {
        currentGallery = 0;
    }

    $('#tout4 img.img_lg').eq(currentGallery).fadeIn(300);
}

So how do I rearrange the actual order of the images, and not just the order in which they are selected?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After much exploration, I decided to take the fisher-yates algorithm and apply it with jquery without requiring cloning, etc.

$('#tout4 img.img_lg').shuffle();

/*
* Shuffle jQuery array of elements - see Fisher-Yates algorithm
*/
jQuery.fn.shuffle = function () {
    var j;
    for (var i = 0; i < this.length; i++) {
        j = Math.floor(Math.random() * this.length);
        $(this[i]).before($(this[j]));
    }
    return this;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...