HTML5圖片拼圖驗證是一種基于圖片的人機交互方式,旨在防止機器人攻擊。該技術最早應用于數字驗證碼,在網頁注冊、登錄、留言等場景中得到廣泛應用。下面是一段HTML5圖片拼圖驗證代碼:
<!DOCTYPE html> <html> <head> <title>HTML5圖片拼圖驗證</title> <style> #puzzle { width: 200px; height: 200px; border: 1px solid #ccc; background-image: url(puzzle.jpg); background-size: 100% 100%; position: relative; } .piece { width: 50px; height: 50px; position: absolute; overflow: hidden; } #piece1 { top: 0; left: 0; } #piece2 { top: 0; left: 50px; } #piece3 { top: 0; left: 100px; } #piece4 { top: 0; left: 150px; } #piece5 { top: 50px; left: 0; } #piece6 { top: 50px; left: 50px; } #piece7 { top: 50px; left: 100px; } #piece8 { top: 50px; left: 150px; } #piece9 { top: 100px; left: 0; } #piece10 { top: 100px; left: 50px; } #piece11 { top: 100px; left: 100px; } #piece12 { top: 100px; left: 150px; } #piece13 { top: 150px; left: 0; } #piece14 { top: 150px; left: 50px; } #piece15 { top: 150px; left: 100px; } #piece16 { top: 150px; left: 150px; } </style> </head> <body> <div id="puzzle"> <div id="piece1" class="piece"></div> <div id="piece2" class="piece"></div> <div id="piece3" class="piece"></div> <div id="piece4" class="piece"></div> <div id="piece5" class="piece"></div> <div id="piece6" class="piece"></div> <div id="piece7" class="piece"></div> <div id="piece8" class="piece"></div> <div id="piece9" class="piece"></div> <div id="piece10" class="piece"></div> <div id="piece11" class="piece"></div> <div id="piece12" class="piece"></div> <div id="piece13" class="piece"></div> <div id="piece14" class="piece"></div> <div id="piece15" class="piece"></div> <div id="piece16" class="piece"></div> </div> <script> var pieces = document.getElementsByClassName("piece"); var offsetX, offsetY; for (var i = 0; i < pieces.length; i++) { pieces[i].addEventListener("mousedown", function(e) { offsetX = e.offsetX; offsetY = e.offsetY; this.style.zIndex = 1; }); pieces[i].addEventListener("mousemove", function(e) { if (e.buttons === 1) { this.style.left = e.pageX - offsetX + "px"; this.style.top = e.pageY - offsetY + "px"; } }); pieces[i].addEventListener("mouseup", function(e) { this.style.zIndex = 0; }); } </script> </body> </html>
上面的代碼實現了一個16塊拼圖,每塊大小為50x50像素,拼成一張200x200像素的圖片。每塊拼圖在鼠標按下時會跟隨鼠標移動,鼠標松開時會停止移動。用戶需要按照預設的拼圖形狀拖動拼圖塊,形成正確的圖片拼圖,以證明自己是人類用戶。