如何在记忆游戏完成时显示全屏半透明覆盖的HTML提示内容?
Great question! Adding a win overlay is a perfect way to celebrate the user's success and add polish to your game. Here's a straightforward, step-by-step solution that integrates seamlessly with your existing jQuery code:
1. Add the Overlay HTML
First, insert this overlay element at the end of your <body> tag (this ensures it sits on top of all other game content):
<div id="winOverlay" class="win-overlay"> <h2>Hey! You've won</h2> </div>
2. Style the Overlay with CSS
Add this CSS to make the overlay full-screen, semi-transparent, and center the winning message:
.win-overlay { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background-color: rgba(0, 0, 0, 0.6); /* Semi-transparent dark background */ display: none; /* Hidden by default */ justify-content: center; align-items: center; z-index: 9999; /* Guarantees it's above all other elements */ } .win-overlay h2 { color: #ffffff; font-size: 3rem; text-align: center; padding: 1rem 2rem; background-color: rgba(255, 255, 255, 0.1); /* Optional: Soften text background */ border-radius: 8px; }
3. Integrate Win Check Logic into Your JavaScript
Update your existing jQuery code to check when all pairs are matched, then trigger the overlay. Here's how to do it:
First, add a helper function to verify the win condition:
function checkIfWon() { // Adjust this to match how you track matched cards (e.g., using a "matched" class) const totalCards = $('.card').length; const matchedCards = $('.card.matched').length; // If every card has been matched if (matchedCards === totalCards) { // Show the overlay with a smooth fade-in effect $('#winOverlay').fadeIn(500); } }
Then, call this function right after you mark a pair as matched in your existing code. For example:
// Inside your existing match-handling code... $('.card1, .card2').addClass('matched'); // Example of marking cards as matched checkIfWon(); // Run the win check after each successful match
Extra Tips:
- Tweak the
rgbavalues in the CSS to adjust the overlay's transparency or color (the fourth value controls opacity: 0 = fully transparent, 1 = fully opaque). - If you don't use a "matched" class, modify
checkIfWonto use your existing tracking method (like a counter variable for matched pairs). - Add interactivity (e.g., restart the game when the overlay is clicked) with this snippet:
$('#winOverlay').click(function() { // Insert your restart game logic here $(this).fadeOut(); });
This implementation will give you a clean, unobtrusive win message that overlays your game while still letting users see their completed matches below.
内容的提问来源于stack exchange,提问作者Gaurav Thantry

