<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> <style> *{ margin:0; padding:0; } .box{ margin-left:20px; } #inp{ display: inline-block; color:pink; font-size: 20px; text-align: center; } .box input{ text-align: center; height:20px; } </style> </head> <body> <div class="box"> <span id="inp"></span> <input type="text" id="zheng" placeholder="请输入验证码"> <button id="btn">提交</button> </div> <script> let sum=[0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f','g','h','i','j','k','l','m','n']; let inp=document.getElementById("inp"); let code; function fun(){ let str=""; for(let i=0;i<4;i++){ let pos=Math.round(Math.random()*24); str+=sum[pos]; } inp.innerHTML=str; return str; } window.onload=function(){ code=fun(); } let btn=document.getElementById("btn"); btn.onclick=function(){ let t=document.getElementById("zheng").value; console.log(t); if(t==code){ alert("验证码输入成功"); code=fun(); document.getElementById("zheng").value=""; } else{ alert("验证码输入错误"); document.getElementById("zheng").value=""; } } </script> </body> </html>