我正在尝试制作一张点击后消失并显示三张随机图像的图像。到目前为止,我认为可能会复制可点击图像两次,只是让那些不可见的图像可以工作,因此它们会更改为其中一个随机图像,并在单击图像后变为可见。如果您对此如何运作有任何其他想法,我真的很想知道!
也有人知道如何制作它,以便图像只能用于三个点中的一个,这样你总能有三个不同的随机图像彼此相邻。
这是我的JS和HTML:
var playerImg;
var playerImg2;
var playerImg3;
var playerArray = ["A1.png", "A2.png", "A3.png", "A4.png", "A5.png", "M1.png", "M2.png", "M3.png", "M4.png", "M5.png", "V1.png", "V2.png", "V3.png", "V4.png", "V5.png", "D1.png", "D2.png", "D3.png"];
function openPack() {
var randomPlayer = (Math.floor(Math.random() * 18) + 1);
playerImg = playerArray[randomPlayer - 1];
document.getElementById("pack").src = "image/" + playerImg;
var randomPlayer2 = (Math.floor(Math.random() * 18) + 1);
playerImg2 = playerArray[randomPlayer2 - 1];
document.getElementById("player2").src = "image/" + playerImg2;
var randomPlayer3 = (Math.floor(Math.random() * 18) + 1);
playerImg3 = playerArray[randomPlayer3 - 1];
document.getElementById("player3").src = "image/" + playerImg3;
}
document.querySelectorAll("img#player2")[0].addEventListener("click", openPack);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<img id="pack" src="image/pack.png" alt="Unopened pack">
<img id="player2" src="image/pack.png" alt="Place for a second player after the pack is opened">
<img id="player3" src="image/pack.png" alt="Place for a third player after the pack is opened">
<img id="veld" src="image/veld.png" alt="Football field with positions">
</body>
<script src="scripts/packs.js"></script>
</html>
如果我忘记说些什么,请告诉我,谢谢!
答案 0 :(得分:0)
这里将排除重复的新openPack
函数
function openPack() {
var playerArraycopy = playerArray.slice();//getting new copy of initial input
function getRandomImg(){
return playerArraycopy.splice([Math.floor(Math.random() * playerArraycopy.length)],1)[0];//calculating a new random image and removing it from copy to exclude duplicates
}
document.getElementById("player2").src = "image/" + getRandomImg();
document.getElementById("pack").src = "image/" + getRandomImg();
document.getElementById("player3").src = "image/" + getRandomImg();
}
检查Array.splice以获取更多信息