HTML5是世界上最流行的標記語言之一,用于創建網站和應用程序。在HTML5中,有許多令人驚嘆的功能,其中之一就是拼圖代碼。拼圖代碼是一種讓您的網站或應用程序更加交互和有趣的方式。
<!DOCTYPE html> <html> <head> <title>HTML5拼圖代碼</title> <style> .puzzle { display: flex; flex-wrap: wrap; width: 300px; height: 300px; } .piece { width: 100px; height: 100px; border: 1px solid black; background-size: 300px 300px; cursor: pointer; } </style> </head> <body> <div id="puzzle" class="puzzle"> <div class="piece" id="piece1" style="background-image: url('puzzle1.png');" onclick="movePiece('piece1')"></div> <div class="piece" id="piece2" style="background-image: url('puzzle2.png');" onclick="movePiece('piece2')"></div> <div class="piece" id="piece3" style="background-image: url('puzzle3.png');" onclick="movePiece('piece3')"></div> <div class="piece" id="piece4" style="background-image: url('puzzle4.png');" onclick="movePiece('piece4')"></div> <div class="piece" id="piece5" style="background-image: url('puzzle5.png');" onclick="movePiece('piece5')"></div> <div class="piece" id="piece6" style="background-image: url('puzzle6.png');" onclick="movePiece('piece6')"></div> <div class="piece" id="piece7" style="background-image: url('puzzle7.png');" onclick="movePiece('piece7')"></div> <div class="piece" id="piece8" style="background-image: url('puzzle8.png');" onclick="movePiece('piece8')"></div> <div class="piece" id="piece9" style="background-image: url('puzzle9.png');" onclick="movePiece('piece9')"></div> </div> <script> function movePiece(id) { var piece = document.getElementById(id); var blank = document.querySelector('.piece.blank'); var temp = {top: piece.style.top, left: piece.style.left}; piece.style.top = blank.style.top; piece.style.left = blank.style.left; blank.style.top = temp.top; blank.style.left = temp.left; piece.classList.remove('blank'); blank.classList.add('blank'); } function shuffle() { var pieces = document.querySelectorAll('.piece'); for (var i = 0; i< 1000; i++) { var randomIndex = Math.floor(Math.random() * pieces.length); movePiece(pieces[randomIndex].id); } } function init() { var pieces = document.querySelectorAll('.piece'); for (var i = 0; i< pieces.length; i++) { if (i === pieces.length - 1) { pieces[i].classList.add('blank'); } pieces[i].style.top = (i % 3) * 100 + 'px'; pieces[i].style.left = Math.floor(i / 3) * 100 + 'px'; } shuffle(); } init(); </script> </body> </html>
以上是一段簡單的HTML5拼圖代碼。這段代碼使用了CSS的flex布局,在一個300x300像素的容器中顯示了九個100x100像素的拼圖塊。當用戶單擊一個拼圖塊時,它會與空白塊交換位置。當拼圖塊處于空白塊所在的位置時,用戶就可以正確地重建原始圖像。