<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>随机验证码校验</title> <style type="text/css"> #code{ 100px; height: 100px; background: #ddd; padding: 10px; line-height: 100px; text-align: center; font-size: 20px; color: red; font-weight: bold; } input{ outline: none } </style> </head> <body> <div id="code"></div> <input type="text" id="newCode"> <input type="button" id="validate" value="验证"> <script type="text/javascript"> window.onload = function(){ var code var codeDiv =document.getElementById('code') var newCode = document.getElementById('newCode') var validate = document.getElementById('validate') creatCode() function creatCode(){//随机生成验证码 code = "" var codeLength = 4 var randomCode = [ 0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','G','K','L','M', 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' ] for(var i=0; i<codeLength; i++){ var index = Math.floor(Math.random() * 36); code += randomCode[index] } codeDiv.innerHTML = code } validate.onclick = function(){// 验证验证码 var inputCode = newCode.value.toUpperCase() if(inputCode==code){//验证通过 alert("验证通过") }else{//验证码不正确 alert("验证码不正确") newCode.value = '' creatCode() } } } </script> </body> </html>
效果