如何确保随机图像不会连续重复

问题描述 投票:0回答:1

我一直在编写一个脚本,当有人单击图像时,它会显示一个随机图像。为了便于解释,我在 codepen 中放置了一个非常基本的示例,其中包含一些带有数字的门图像。

我已经能够通过 onclick 使图像随机化,但有时图像会连续重复,因此您必须单击按钮几次才能弹出新图像。

例如,当有人点击图片时,显示的随机图片可以是图1、图4、图4、图3的顺序。作为一般示例。

我需要做什么才能停止连续显示图片?我不介意照片是否再次出现,只是不直接背对背显示,因为这使得用户必须多次单击按钮才能更改图像。

我尝试过查看不同的线程,但我发现似乎没有什么对我有用。

HTML

<body>
       <div onLoad="pickimg2">
 
    <img src="https://websitetestsone.neocities.org/images/door-test-default.png" name="randimg" border=0 usemap="#image_map">
<map name="image_map">
  <area alt="" title="" href="" coords="180,378,335,407" shape="rect" onClick="pickimg2();return false;">
</map>
</div>

Javascript

var myImages1 = new Array();
myImages1.push("https://websitetestsone.neocities.org/images/door-test-1.png");
myImages1.push("https://websitetestsone.neocities.org/images/door-test-2.png");
myImages1.push("https://websitetestsone.neocities.org/images/door-test-3.png");
myImages1.push("https://websitetestsone.neocities.org/images/door-test-4.png");
myImages1.push("https://websitetestsone.neocities.org/images/door-test-5.png");

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function pickimg2() {
  document.randimg.src = myImages1[getRandomInt(0, myImages1.length - 1)];
}

Codepen 链接 https://codepen.io/hrussio/pen/PogdPom

谢谢!

javascript html image imagemap
1个回答
0
投票

跟踪最后显示的图像的索引,以便确保它不会重复。

var lastImageIndex = -1; // Initialize last shown image index = -1

function pickimg2() {
  var randomIndex;
  do {
    randomIndex = getRandomInt(0, myImages1.length - 1);
  } while (randomIndex === lastImageIndex); // Generate random index until different from last index
  document.randimg.src = myImages1[randomIndex];
  lastImageIndex = randomIndex; // Update last shown image index
}
© www.soinside.com 2019 - 2024. All rights reserved.