【问题标题】:How to display a random background image while avoiding repetition of those images?如何在避免重复这些图像的同时显示随机背景图像?
【发布时间】:2018-11-06 15:03:49
【问题描述】:

我有这个 JS 代码,其中包括(当前)4 个图像的数组和一个选择随机图像的函数:

    const scenes = ['url(scenes/scene1.jpg)', 'url(scenes/scene2.jpg)', 'url(scenes/scene3.jpg)', 'url(scenes/scene1.jpg)'];

    function randomScene() {
        const shuffle = Math.floor(Math.random() * (scenes.length));
        document.getElementById('bg-switch').style.backgroundImage = scenes[shuffle];
    };

然后我有一个 HTML 按钮 - 如果单击它,它会执行“randomScene()”,并显示来自名为“scenes”的数组中的图像。

    <section id="bg-switch">
        <div class="container text-center">
            <a><button type="button" onclick="randomScene()">Click!</button></a>
        </div>
    </section>

问题:我想避免在单击按钮时连续显示同一图像两次。

  1. 我想从数组中删除已显示的图像。
  2. 我想重置(随机播放?)数组,一旦从数组中删除所有元素,因此单击按钮会继续显示图像。

【问题讨论】:

  • 最简单的方法可能是sort the array randomly,然后按顺序逐步完成。
  • 我会按照 Daniel 建议的方式进行。打乱数组,然后您可以遍历它,而不必再担心重复或随机化或清理。

标签: javascript arrays random


【解决方案1】:

您可以创建一个变量并将图像路径存储在其中。在每次点击时检查当前图像是否与随机生成的图像相同。如果没有,则将其添加到后台并更新 currImg 变量

const scenes = ['url(scenes/scene1.jpg)', 'url(scenes/scene2.jpg)', 'url(scenes/scene3.jpg)', 'url(scenes/scene1.jpg)'];

let currImg = ''

function randomScene() {
  const shuffle = Math.floor(Math.random() * (scenes.length));
  if (scenes[shuffle] === currImg) {
    randomScene()
  } else {
    document.getElementById('bg-switch').style.backgroundImage = scenes[shuffle];
    currImg = scenes[shuffle]
  }
};
<section id="bg-switch">
  <div class="container text-center">
    <a><button type="button" onclick="randomScene()">Click!</button></a>
  </div>
</section>

【讨论】:

  • 谢谢。现在它不会连续两次选择相同的图像。我也应该尝试 Daniel Beck 和 IceMetalPunk 建议的方法(循环遍历整个数组),但是您的解决方案对我来说是向前迈出了一大步!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-16
  • 2015-06-08
  • 1970-01-01
  • 1970-01-01
  • 2012-02-08
  • 1970-01-01
相关资源
最近更新 更多