簡體   English   中英

如何從數組中選擇隨機圖像並將其用作 javascript 和 html 中其他圖像的來源

[英]How do I choose a random image from an array and use it as a source for other images in javascript and html

我正在嘗試制作一個網站,我需要生成隨機圖像,然后用作輸入按鈕。

當我嘗試使用圖像不顯示的結果時。

我需要幫助的事情是顯示圖像 bc 選擇隨機圖像的代碼就像在名稱下一樣,但我不知道如何使用名稱作為按鈕事物的來源

如果有任何意義,我希望生成的圖像替換按鈕

我相信你正在嘗試這樣做:

HTML:

<html>
  <body>
    <a href="#" onclick="alert('You clicked!')">
      <img src="" id="button_img" style="height: 100px;width: 100px;">
    </a>
  </body>
</html>

記者:

<script>

  //array of links for images
  var array_of_images = [
    "https://www.pngitem.com/pimgs/m/97-974332_yellow-duck-png-download-image-transparent-background-rubber.png",
    "https://www.shareicon.net/data/256x256/2015/07/31/78089_make_512x512.png",
    "https://www.pngitem.com/pimgs/m/97-974413_rubber-duck-png-transparent-background-duck-clipart-png.png"
    ];

  //generate random number form 0-3
  var randomNum = Math.floor(Math.random()*3);

  //using the random number to choose a link from the array
  document.getElementById('button_img').src = array_of_images[randomNum];

</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM