2013-02-20 100 views
1

第I頁reference如何隨機化圖像的順序?

部分在圖像被加載:

<div id="lighttable"> 

<img src="http://throwingupthew.com/girls/01.jpg" alt="01" /> 
<img src="http://throwingupthew.com/girls/02.jpg" alt="02" /> 
<img src="http://throwingupthew.com/girls/03.jpg" alt="03" /> 

etc.... 

</div> 

我如何隨機圖像的順序? 請記住我不知道在index.html中放置任何代碼/答案的位置

謝謝。

+1

通過先做一點研究開始:http://stackoverflow.com/questions/5329201/jquery-move-elements-into-a-random-order – Blender 2013-02-20 01:07:48

+0

你想用JavaScript或...隨機化他們嗎? – 2013-02-20 01:08:50

+0

我想以最簡單的方式隨機化。除了調整值來改變結果之外,我對HTML/javascript編碼一無所知。 – 2013-02-20 01:12:26

回答

0

你的HTML改成這樣:

<div id="lighttable"> 

<img id="girl1" src="" alt="01" /> 
<img id="girl2" src="" alt="02" /> 
<img id="girl3" src="" alt="03" /> 

etc.... 

</div> 

將這個正確的頁面的</head>標籤之前

<script type="text/javascript"> 
var array = ['http://throwingupthew.com/girls/01.jpg','http://throwingupthew.com/girls/02.jpg','http://throwingupthew.com/girls/03.jpg']; 
function shuffle(array) { 
var currentIndex = array.length; 
var temporaryValue; 
var randomIndex; 
    while (0 !== currentIndex) { 
    randomIndex = Math.floor(Math.random() * currentIndex); 
    currentIndex -= 1; 
    temporaryValue = array[currentIndex]; 
    array[currentIndex] = array[randomIndex]; 
    array[randomIndex] = temporaryValue; 
    } 
    return array; 
} 
var shuffled_images = shuffle(array); 
for(var i=0;i<3;i++) { 
document.getElementById('girl' + (i+1)).src = shuffled_images[i] ; 
} 
</script> 

由於Randomizing(Shuffling) an Array這個頁面,我是能夠使這個腳本爲你: )

這裏是工作JSFiddle :)