Javascript 如何随机排列卡片
每次随机上传应用程序时,如何安排卡片? 我试图将卡片插入阵列,但尝试失败 不成功的 这是一款卡片记忆游戏。 我可以在DIV中为我的元素设置一个位置吗? 我的HTML代码是三张八张卡片,每张卡片在一个分区中, 和div name中的所有卡:allCardJavascript 如何随机排列卡片,javascript,html,Javascript,Html,每次随机上传应用程序时,如何安排卡片? 我试图将卡片插入阵列,但尝试失败 不成功的 这是一款卡片记忆游戏。 我可以在DIV中为我的元素设置一个位置吗? 我的HTML代码是三张八张卡片,每张卡片在一个分区中, 和div name中的所有卡:allCard 我构建了一个独立的原型来实现这一点。在代码中工作应该很容易 代码笔: 首先,我们将把卡片放在一个JS数组中,而不是硬编码到HTML中 接下来,我们将该数组积分洗牌到该堆栈溢出答案: 然后,我们使用.forEach循环遍历现在已洗牌的数组-在这个循
我构建了一个独立的原型来实现这一点。在代码中工作应该很容易 代码笔: 首先,我们将把卡片放在一个JS数组中,而不是硬编码到HTML中 接下来,我们将该数组积分洗牌到该堆栈溢出答案: 然后,我们使用.forEach循环遍历现在已洗牌的数组-在这个循环过程中,为每张卡创建DOM元素,然后将其附加到页面 如果您需要进一步的澄清,请告诉我
<html>
<head></head>
<body>
<div class="card-container"></div>
</body>
</html>
如果您提供HTML和JS代码片段,我很乐意为您尝试一下。谢谢,我也添加了HTML
<html>
<head></head>
<body>
<div class="card-container"></div>
</body>
</html>
.card-container {
display: flex;
justify-content: space-between;
}
.card {
display: flex;
}
.card .front,
.card .back {
width: 100px;
height: 160px;
border: 1px solid #CCC;
background-color: #F3F3F3;
display: flex;
justify-content: center;
align-items: center;
text-align: center;
}
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
var cards = ['Ace of Spades', 'Queen of Hearts', 'Two of Hearts', 'Five of Diamonds'];
cards = shuffle(cards)
cards.forEach(function(card) {
var elem = document.createElement('div');
elem.classList.add('card');
var front = document.createElement('div');
front.appendChild(document.createTextNode(card));
front.classList.add('front');
var back = document.createElement('div');
back.appendChild(document.createTextNode('BACK'));
back.classList.add('back');
elem.appendChild(front);
elem.appendChild(back);
document.querySelector('.card-container').appendChild(elem);
console.log(card)
})