<html>
  <head>
    <title>Memory Game</title>
    <style>
      body {
        background-color: #f0f0f0;
      }
      #game-container {
        width: 400px;
        margin: 0 auto;
        padding: 20px;
      }
      .box {
        width: 80px;
        height: 80px;
        margin: 5px;
        float: left;
        background-color: #39f;
        font-size: 50px;
        text-align: center;
        color: #fff;
      }
    </style>
  </head>
  <body>
    <div id='game-container'>
      <div class='box' data-name='1'>1</div>
      <div class='box' data-name='2'>2</div>
      <div class='box' data-name='3'>3</div>
      <div class='box' data-name='4'>4</div>
      <div class='box' data-name='5'>5</div>
      <div class='box' data-name='6'>6</div>
    </div>
<pre><code>&lt;script&gt;
  let boxes = document.querySelectorAll('.box');
  let activeBoxes = [];
  let activeNames = [];

  boxes.forEach(function(box) {
    box.addEventListener('click', function() {
      if (activeBoxes.length &lt; 2) {
        box.style.backgroundColor = '#f00';
        activeBoxes.push(box);
        activeNames.push(box.dataset.name);

        if (activeBoxes.length === 2) {
          if (activeNames[0] === activeNames[1]) {
            activeBoxes.forEach(function(box) {
              box.style.backgroundColor = '#0f0';
            });
          } else {
            setTimeout(function() {
              activeBoxes.forEach(function(box) {
                box.style.backgroundColor = '#39f';
              });
            }, 1000);
          }
          activeBoxes = [];
          activeNames = [];
        }
      }
    });
  });
&lt;/script&gt;
</code></pre>
  </body>
</html>
Simple HTML Memory Game: Code & Tutorial

原文地址: https://www.cveoy.top/t/topic/lml6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录