<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>验证码</title> <style> .get{ cursor: pointer; } .reset{ display: none; } .reset span{ color:red; } </style> </head> <body> <input type="text"><button>确定</button> <p class="get">获取验证码</p> <p class="reset">重新获取验证码<span>10</span>s</p> </body> <script> function $(el) { return document.querySelector(el); } let val=""; let timer=null; function stop() { clearInterval(timer); timer=null; } $(".get").onclick=function(){ this.style.display="none"; $(".reset").style.display="block"; var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; function generateMixed(n) { var res = ""; for(var i = 0; i < n; i++) { var id=Math.ceil(Math.random() * 35); res +=chars[id]; } return res; } var num1=generateMixed(4); val=num1; alert(num1); var i=10; timer=setInterval(() => { i--; $(".reset span").innerText=i; if(i===0){ stop(); $(".reset").style.display="none"; $(".get").style.display="block"; } }, 1000); } $("button").onclick=function(){ console.log(val); if(val!=$("input").value){ console.log("输入错误"); $("input").value=""; return; } } </script> </html>