您好,我有一个内存游戏,这里有演示。
https://kuochye.github.io/memorygame/
我遇到最后一张卡片未翻转的问题,并且不知道原因。
document.querySelectorAll(".flip-container").forEach(card => card.classList.add("clicked"));
setTimeout(function () {
document.querySelectorAll(".flip-container").forEach(card =>
card.classList.remove("clicked"));
}, 30000);
^ 这就是我在卡片翻转之前将卡片展示 30 秒的做法。但不知何故,最后一张卡片没有显示。
// Build single card
var buildCardNode = function (index, value, isRevealed, width, height) {
var flipContainer = document.createElement("li");
var flipper = document.createElement("div");
var front = document.createElement("a");
var back = document.createElement("a");
flipContainer.index = index;
flipContainer.style.width = width;
flipContainer.style.height = height;
flipContainer.classList.add("flip-container");
if (isRevealed) {
flipContainer.classList.add("clicked");
}
flipper.classList.add("flipper");
front.classList.add("front");
front.setAttribute("href", "#");
back.classList.add("back");
back.classList.add("card-" + value);
back.setAttribute("href", "#");
flipper.appendChild(front);
flipper.appendChild(back);
flipContainer.appendChild(flipper);
flipContainer.addEventListener('click', handleFlipCard);
document.querySelectorAll(".flip-container").forEach(card => card.classList.add("clicked"));
setTimeout(function () {
document.querySelectorAll(".flip-container").forEach(card =>
card.classList.remove("clicked"));
}, 30000);
return flipContainer;
};
最佳答案
你要做的就是寻找每张已经添加的卡片并将其翻转。那很好,但是您需要在将每张卡片添加到文档之前执行此操作。因此,对于添加的每张卡,它都会找到之前添加的每张卡并将其翻转。
您想做两件事之一:
a.将所有卡片添加到文档后翻转它们(通过将第一段代码从 buildCardNode 函数移到调用它的位置)。
b.在添加到文档之前直接翻转每张卡片(不使用 document.querySelectorAll.forEach,而是使用 FlipContainer.classList.add/remove)。
关于Javascript内存卡游戏最后一张牌不翻转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47107252/