You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现记忆卡牌游戏中卡牌的水平居中显示?

记忆卡牌水平居中解决方案

核心修改说明

  • 移除JavaScript中覆盖网格布局的flex设置,保留CSS定义的grid布局
  • 调整网格容器属性,确保卡牌组在页面中水平居中

修改后的完整代码

JavaScript文件(game.js)

let cards = [];
let cardElements = [];
let flippedCards = [];
let matchedCards = [];
let tries = 0;

function startGame(numCards) {
  document.getElementById("start-screen").style.display = "none";
  document.getElementById("game-container").style.display = "flex";
  // 移除flex布局覆盖,保留CSS的grid设置
  document.getElementById("tries-counter").innerText = "Tries: 0";
  tries = 0;

  cards = [];
  let icons = [
    "yin-yang",
    "anchor",
    "baby",
    "bicycle",
    "wifi",
    "user-graduate",
    "truck-monster",
    "tablet-alt",
  ];
  for (let i = 0; i < numCards / 2; i++) {
    cards.push(icons[i]);
    cards.push(icons[i]);
  }
  createCards();
}

function createCards() {
  let gameBoard = document.getElementById("game-board");
  gameBoard.innerHTML = "";
  cardElements = [];
  flippedCards = [];
  matchedCards = [];
  cards.sort(() => Math.random() - 0.5);

  for (let i = 0; i < cards.length; i++) {
    let card = document.createElement("div");
    card.className = "card";
    card.dataset.value = cards[i];
    card.addEventListener("click", flipCard);
    gameBoard.appendChild(card);
    cardElements.push(card);
  }
}

function flipCard() {
  if (flippedCards.length === 2 || this === flippedCards[0]) return;
  this.innerHTML = `<i class="fas fa-${this.dataset.value}"></i>`;
  flippedCards.push(this);
  if (flippedCards.length === 2) {
    tries++;
    document.getElementById("tries-counter").innerText = `Tries: ${tries}`;
    setTimeout(checkForMatch, 1000);
  }
}

function checkForMatch() {
  let isMatch = flippedCards[0].dataset.value === flippedCards[1].dataset.value;
  if (isMatch) {
    flippedCards.forEach((card) => card.classList.add("matched"));
    matchedCards = matchedCards.concat(flippedCards);
  } else {
    flippedCards.forEach((card) => {
      card.innerHTML = "";
    });
  }
  flippedCards = [];
  if (matchedCards.length === cardElements.length)
    toastr["success"](
      "You won in " + tries + " tries! Refresh the page to play again!"
    );
}

CSS文件(styles.css)

body {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
  margin: 0;
  font-family: Arial, sans-serif;
  width: 100vw;
}

#game-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  flex-direction: column;
  gap: 1rem;
  padding: 1rem;
  max-width: 90vw;
  max-height: 90vh;
}

#game-board {
  display: grid;
  /* 固定列宽并自动适配容器,保持卡牌尺寸一致 */
  grid-template-columns: repeat(auto-fit, 100px);
  gap: 1rem;
  padding: 1rem;
  place-self: center;
  box-sizing: border-box;
  max-width: 100vw;
  /* 让网格整体在容器中水平居中 */
  justify-content: center;
}

.card {
  min-width: 100px;
  height: 100px;
  background-color: #000;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  font-size: 2em;
  cursor: pointer;
  border-radius: 10px;
  box-shadow: 0 10px 10px rgba(0, 0, 0, 0.2);
  transition: transform 0.2s;
}

.card:hover {
  transform: scale(1.1);
}

.matched {
  background-color: #0f0 !important;
}

#tries-counter {
  margin-top: 20px;
  font-size: 1.5em;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}

button {
  font-size: 2em;
  padding: 0.5em 1em;
  border-radius: 10px;
  border: none;
  background-color: #000;
  color: #fff;
  cursor: pointer;
  margin: 0.5em;
  box-shadow: 0 10px 10px rgba(0, 0, 0, 0.2);
  transition: transform 0.2s;
}

button:hover {
  transform: scale(1.1);
}

#start-screen {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
}

HTML文件(index.html)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Memory Card Game</title>
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"
    />
    <script
      src="https://code.jquery.com/jquery-3.7.1.min.js"
      integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
      crossorigin="anonymous"
    ></script>
    <script src="toastr.min.js"></script>
    <link rel="stylesheet" href="toastr.min.css" />
    <link rel="stylesheet" href="css/styles.css" />
  </head>
  <body>
    <div id="start-screen">
      <h1>Select card game size</h1>
      <div>
        <button onclick="startGame(4)">4</button>
        <button onclick="startGame(6)">6</button>
        <button onclick="startGame(8)">8</button>
        <button onclick="startGame(10)">10</button>
        <button onclick="startGame(12)">12</button>
      </div>
    </div>
    <div id="game-container" style="display: none">
      <div id="tries-counter">Tries: 0</div>
      <div id="game-board"></div>
    </div>

    <script src="js/game.js"></script>
  </body>
</html>

内容的提问来源于stack exchange,提问作者Jordan Thompson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 10:19:52