如何实现随机图片不连续重复显示?
解决图片随机切换时连续重复的问题
要避免连续重复显示同一张图片,只需添加一个变量记录上一次选中的图片索引,生成随机索引时跳过当前索引即可。修改后的代码如下:
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 = [ "https://websitetestsone.neocities.org/images/door-test-1.png", "https://websitetestsone.neocities.org/images/door-test-2.png", "https://websitetestsone.neocities.org/images/door-test-3.png", "https://websitetestsone.neocities.org/images/door-test-4.png", "https://websitetestsone.neocities.org/images/door-test-5.png" ]; // 记录上一次选中的图片索引,初始值设为-1(与图片索引范围0-4不重合) let lastIndex = -1; function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function pickimg2() { let currentIndex; // 生成随机索引,直到和上一次的索引不同 do { currentIndex = getRandomInt(0, myImages1.length - 1); } while (currentIndex === lastIndex); // 更新记录的索引,并切换图片 lastIndex = currentIndex; document.randimg.src = myImages1[currentIndex]; }
关键说明
- 新增
lastIndex变量存储上一次选中的图片索引,初始值设为-1(确保第一次生成的索引不会重复)。 - 在
pickimg2函数中,通过do-while循环生成随机索引,直到得到与lastIndex不同的值,避免连续重复。 - 每次切换图片后更新
lastIndex,保证下一次生成索引时能正确对比。
这样修改后,图片可以重复出现,但不会连续显示同一张。
内容的提问来源于stack exchange,提问作者hrussio
相关产品推荐
相关产品推荐

