繁体   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