js编写验证码

这是一个简单的js编写的验证码,自己已经亲自验证,没有问题了

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <title>js编写验证码</title>
 5     <style type="text/css" >  
 6 
 7         .code   
 8         {   
 9             background-image:url(code.jpg);   
10             font-family:Arial;   
11             font-style:italic;   
12             color:Red;   
13             border:0;   
14             padding:2px 3px;   
15             letter-spacing:3px;   
16             font-weight:bolder;   
17         }   
18 
19         .unchanged   
20         {   
21             border:0;   
22         }   
23     </style>  
24     <script language="javascript" type="text/javascript">
25      var code ; //在全局 定义验证码   
26      function createCode()   
27      {    
28        code = "";   
29        var codeLength = 6;//验证码的长度   
30        var checkCode = document.getElementById("checkCode");   
31        var selectChar = new Array(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');//所有候选组成验证码的字符,当然也可以用中文的     
32        for(var i=0;i<codeLength;i++)   
33        {   
34 
35        var charIndex = Math.floor(Math.random()*36);   //Math.random得到0-36中随机的一个数,floor取整数部分
36        code +=selectChar[charIndex];   
37        }   
38 //       alert(code);   
39        if(checkCode)   
40        {   
41          checkCode.className="code";   
42          checkCode.value = code;   
43        }   
44      }   
45 
46       function validate ()   
47      {   
48 
49        var inputCode = document.getElementById("input1").value;   
50        if(inputCode.length <=0)   
51        {   
52            alert("请输入验证码!");   
53        }   
54        else if(inputCode != code )   
55        {   
56          alert("验证码输入错误!");   
57           createCode();//刷新验证码   
58        }   
59        else   
60        {   
61          alert("^-^ OK");   
62        }   
63     
64      }   
65 
66     </script>  
67 </head>
68 <body onload="createCode()" >
69 <form  action="#">
70 
71   <input  type="text"   id="input1" />
72 
73 <input type="text" onclick="createCode()" readonly="readonly" id="checkCode" class="unchanged" style=" 80px"  /><br />  
74 
75     <input id="Button1"  onclick="validate();" type="button" value="确定" />    
76 
77 </form>  
78 </body>
79 </html>

一定要在body出onload不然第一次加载的时候看不到验证码

原文地址:https://www.cnblogs.com/tutoo/p/4048736.html