HTML5記憶翻牌源代碼
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>記憶翻牌游戲</title> <style> .card { width: 100px; height: 100px; background-color: blue; margin: 20px; float: left; perspective: 1000px; position: relative; cursor: pointer; } .card .front, .card .back { width: 100%; height: 100%; position: absolute; top: 0; left: 0; -webkit-backface-visibility: hidden; backface-visibility: hidden; } .card .front { background-color: green; z-index: 2; } .card .back { transform: rotateY(180deg); background-color: red; z-index: 1; } .card.flipped .front { transform: rotateY(180deg); z-index: 1; } .card.flipped .back { transform: rotateY(0); z-index: 2; } </style> </head> <body> <div class="card" data-card="A"> <div class="front">A</div> <div class="back"></div> </div> <div class="card" data-card="B"> <div class="front">B</div> <div class="back"></div> </div> <div class="card" data-card="C"> <div class="front">C</div> <div class="back"></div> </div> </body> <script> var cards = document.querySelectorAll('.card'); var flippedCards = []; var matchedCards = []; var canFlip = true; for (var i = 0; i < cards.length; i++) { cards[i].addEventListener('click', function() { if (canFlip && !matchedCards.includes(this.dataset.card) && !flippedCards.includes(this)) { this.classList.add('flipped'); flippedCards.push(this); if (flippedCards.length === 2) { canFlip = false; setTimeout(function() { if (flippedCards[0].dataset.card === flippedCards[1].dataset.card) { flippedCards[0].classList.add('matched'); flippedCards[1].classList.add('matched'); matchedCards.push(flippedCards[0].dataset.card); } else { flippedCards[0].classList.remove('flipped'); flippedCards[1].classList.remove('flipped'); } flippedCards = []; canFlip = true; }, 1000); } } }); } </script> </html>