【问题标题】:Randomly Changing Images from an Array of Images从图像数组中随机更改图像
【发布时间】:2016-10-21 17:34:30
【问题描述】:

标题基本上说明了一切。

我正在尝试将图像更改为图像数组中的随机图像(希望有意义,哈哈)。

如何创建一个图像数组,然后在单击某些内容时将图像更改为随机图像?

<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.

【问题讨论】:

  • 什么时候没有显示?
  • 就像在 CSS 中一样。 ('显示:无')

标签: jquery html image random


【解决方案1】:

在这种情况下,您可以将图像存储在某处,然后将它们的路径存储在数组中并像这样调用它们:

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;

}

【讨论】:

  • 鉴于此,您可以更改函数以根据时间随机更改图像(幻灯片样式)或onclick
【解决方案2】:

这个example 展示了如何使用常规(非 Ajax)网页做到这一点,其中图像列在数组中,生成的随机数用于从中选择特定图像。另一种方法是在服务器端(例如 NodeJS)实现随机图像选择,并在客户端使用相同的 Ajax 调用来触发服务器选择器逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多