我有可用的javascipt代码,可在单击卡后显示图像数组中的随机图像。一共有3张卡片,当他们单击Clickong后,每个人都会看到不重复的随机图像。我现在的目标是确保例如在这3张卡中的一张中必须看到一个特定的图像2.jpg,并且仅在其中一张卡中显示该图像。这是我的HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Card</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="wrap">
<div class="card">
<div class="front" onclick="getCard(0)"><img class="img1" src="https://lp.rustaro.ru/wp-content/uploads/transformation/cards/1.jpg" alt=""></div>
<div class="back"><img class="img1" src="" name="randimg1"></div>
</div>
<div class="card">
<div class="front" onclick="getCard(1)"><img class="img1" src="https://lp.rustaro.ru/wp-content/uploads/transformation/cards/1.jpg" alt=""></div>
<div class="back"><img class="img1" src="" name="randimg2"></div>
</div>
<div class="card">
<div class="front" onclick="getCard(2)"><img class="img1" src="https://lp.rustaro.ru/wp-content/uploads/transformation/cards/1.jpg" alt=""></div>
<div class="back"><img class="img1" src="" name="randimg3"></div>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
和JavaScript部分:
// Turning images
var images = [];
(function() {
generateCards()
})();
var cards = document.querySelectorAll('.card');
Array.from(cards).forEach(function(card) {
card.addEventListener('click', function() {
Array.from(card.querySelectorAll('.back, .front')).forEach(function(el) {
['back', 'front'].forEach(function(s) {
el.classList.toggle(s)
});
});
});
});
//Displaying different images on click
function cardImg(index) {
var cardNewImg = randomIntFromInterval(2,10);
if (images[index] !== undefined)
{
images[index] = -1;
}
while (images.indexOf(cardNewImg)!= -1){
cardNewImg = randomIntFromInterval(2,11);
}
images[index] = cardNewImg;
}
function generateCards() {
for (var i = 0; i < 3; i++) {
cardImg(i);
}
}
function getCard(index) {
if(!images[index].valid) {
cardImg(index)
}
document["randimg"+(index + 1)].src = "https://lp.rustaro.ru/wp-content/uploads/transformation/cards/" + images[index] + ".jpg";
}
function randomIntFromInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
这是工作pen上的链接。任何帮助将不胜感激。
答案 0 :(得分:0)
这将确保第一张(最左边的)卡始终为nbr 2
function cardImg(index) {
var cardNewImg = randomIntFromInterval(2,10);
if (images[index] !== undefined)
{
images[index] = -1;
}
while (images.indexOf(cardNewImg)!= -1)
{
cardNewImg = randomIntFromInterval(2,11);
}
if (images.indexOf(2) == -1)
{
images[index] = 2;
}else{
images[index] = cardNewImg;}
}