<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>idCode</title> <style> .code{ font-family:Arial; font-style:italic; color:red; border:0; padding:2px 3px; letter-spacing:3px; font-weight:bold; background: yellow; opacity: 0.8; } #checkCode{ width: 60px; text-align: center; } </style> </head> <form action="#"> <input type="text" id="inValue"> <input type="text" readonly="readonly" id="checkCode" class="code"> <br> <br> <input id="btn" type="button" value="确定"> </form> <script> window.onload = function(){ createCode(); var checkCode = document.getElementById_x_x_x("checkCode"); var btn = document.getElementById_x_x_x("btn"); checkCode.onclick = function(){ createCode(); } btn.onclick = function(){ validate(); } } var code;//在全局定义验证码 function createCode(){ code = "";//code存储字符串 var codeLength = 4;//验证码的长度 var selectChar = [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','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'];//所有候选组成验证码的字符,当然也可以用中文的 var getRandomColor = function(){ return '#'+(Math.random()*0xffffff<<0).toString(16); }//随机生成背景颜色 for(var i=0; i < codeLength; i ++) { var charIndex = Math.floor(Math.random()*62); //alert(charIndex); code += selectChar[charIndex]; } //alert(code); if(checkCode) { checkCode.style.background = getRandomColor(); checkCode.value = code; } } function validate(){ var inputCode = document. getElementById("inValue").value; if(inputCode.length<=0) { alert("请输入验证码!"); } else if(inputCode.toUpperCase()!=code.toUpperCase()) { alert("验证码输入错误!"); createCode();//刷新验证码 } else { alert("输入正确,验证成功"); } } </script> </body> </html>