基本上你想要做的是把所有的圖像放入一個數組,然後洗牌數組的順序。在更改數組的順序後,可以將新數組輸出回屏幕。
我已經彙集了一個示例來向您展示如何使用jQuery正確執行此操作。下面的示例會在您每次按「隨機播放」按鈕時隨機隨機播放。
請注意,我將您的div的名稱從id =「two」更改爲id =「picContainer」。
HTML:
<div id="picContainer">
<img id="pict_01" src="https://www.khanacademy.org/images/topic-icons/math/doodling-in-math.png?v2" />
<img id="pict_02" src="http://www.milldamschool.ik.org/img/d666f5fc-db14-11de-a689-0014220c8f46-5812526.jpg" />
<img id="pict_03" src="http://www.birdsontheblog.co.uk/wp-content/uploads/2010/05/maths.jpg" />
</div>
JS(jQuery的):
//grab the div that contains our images
var container = $('#picContainer');
//grab our button
var button = $('.shuffleMe');
//search through div and add all images to an array
var images = $(container).find('img');
//console out the images array
console.log('images: ', images);
//function to shuffle our array
//using the Fisher-Yates Shuffle.
//See https://github.com/coolaj86/knuth-shuffle
function shuffleArray(array) {
var currentIndex = array.length, temporaryValue, randomIndex ;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
//shuffle our image arrray and create a new array with random ordered images
var randomImages = shuffleArray(images);
//console out the images to we can see they changed order
console.log("random image: ", randomImages);
//empty our image container and
//append our images in a new random order
//to the same container
function renderImages(array){
$(container).empty();
$.each(array, function(index, value) {
$(container).append(value);
});
}
//call the renderImages function when our button is pressed
$(button).on("click", function(){
//render the random images to the screen
randomImages = shuffleArray(images);
renderImages(randomImages);
});
我希望這有助於。
http://codepen.io/anon/pen/zkoCl
你必須要學習javascript我的朋友。檢查eloquentjavascript.net。 – 2014-10-31 01:23:50