2016-10-21 30 views
0

標題基本上說明了一切。從圖像陣列中隨機更改圖像

我想將圖像從圖像數組中隨機圖像(希望是有道理的哈哈)。

如何創建圖像數組,然後在點擊某個圖像時將圖像更改爲隨機圖像?

<h1>These are just placeholders</h1> 
<p>I just want these images to randomly change to an image from an array of images each time they are shown (when "display" isn't "none")</p> 
<img src="https://pixabay.com/static/uploads/photo/2013/11/21/07/30/icon-214446_960_720.jpg" class="newsAD"></img> 
<img src="https://pixabay.com/static/uploads/photo/2013/11/21/07/30/according-to-214445_960_720.jpg" class="newsAD"></img> 

<style> 
    .newsAD { 
     width: 150px; 
     height: 150px; 
     margin-left: 50px; 
     background: skyblue; 
     cursor: default; 
     box-shadow: 1px 2px 5px 1px rgba(0, 0, 0, 0.4); 
    } 
</style> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"> 
function changeImageToRandomImage() { 
// something here that changes image to random image from array of images 
} 
</script> 

Here's a fiddle.

+0

時顯示ISN」沒有? – Tonza

+0

像CSS一樣。 ('display:none') –

回答

2

在這種情況下,你會在一些地方保存圖像,然後它們的路徑存放在數組中,並呼籲他們像這樣:

HTML

<img onclick="changeImageToRandomImage()" id="image" src="img/image_0.jpg"> 

的JavaScript

function changeImageToRandomImage() { 
    images = ['img/image_1.jpg', 'img/image_2.jpg','img/image_3.jpg','img/image_4.jpg']; 

    var random = images[Math.floor(Math.random()*images.length)]; 
    document.getElementById('image').src= random; 

} 
+0

鑑於此,您可以更改功能以隨時間變化圖像(幻燈片顯示樣式)或「onclick」。 –

+0

謝謝老兄,效果很棒! ^^ –

+0

工作小提琴:https://jsfiddle.net/d1ec07p2/8/ –

0

example顯示瞭如何做到這一點與常規(非Ajax)網頁,圖像被以陣列和用於從所選擇的特定圖像產生的隨機數列它。另一種方法是在服務器端實現隨機圖像選擇(例如NodeJS),並在客戶端使用相同的Ajax調用來觸發服務器選擇器邏輯。