js实现验证码

来源:互联网 发布:linux清空所有文件内容 编辑:程序博客网 时间:2024/06/11 00:29

一.js实现验证码:

第一步:建一个login.htm,一个code.js文件,一个code.css文件,准备一张图片code.jpg

第二步:编写login.htm文件,内容为:

[html] view plaincopyprint?
  1. <html>      
  2. <head>      
  3. <script language = "javascript" src = "code.js"></script>      
  4. <link rel="stylesheet" type="text/css" href="code.css">      
  5. </head>      
  6. <body onload="createCode();">      
  7. <form>      
  8. <center>验证码:<input type="text" id="input1" />      
  9. <input type="text" id="checkCode" class="code" style="width: 55px" /> <a href="#" onclick="createCode()">看不清楚</a>      
  10. <input id="Button1" onclick="validate();" type="button" value="确定" /></center>      
  11. </form>      
  12. </body>      
  13. </html>     


第三步:编写code.css文件,内容为:

[html] view plaincopyprint?
  1. .code{      
  2. background-image:url(w1.jpg);      
  3. font-family:Arial;      
  4. font-style:italic;      
  5. color:Red;      
  6. border:0;      
  7. padding:2px 3px;      
  8. letter-spacing:3px;      
  9. font-weight:bolder;      
  10. }       


第四步:编写code.js文件,内容为:

[html] view plaincopyprint?
  1. var code ; //在全局 定义验证码      
  2. function createCode(){       
  3. code = "";      
  4. var codeLength = 4;//验证码的长度      
  5. var checkCode = document.getElementById("checkCode");      
  6. checkCode.value = "";      
  7. var selectChar = new Array(1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f','g','h','j','k','l','m','n','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z');      
  8.       
  9. for(var i=0;i<codeLength;i++) {      
  10.    var charIndex = Math.floor(Math.random()*60);      
  11.   code +=selectChar[charIndex];      
  12. }      
  13. if(code.length != codeLength){      
  14.   createCode();      
  15. }      
  16. checkCode.value = code;      
  17. }      
  18.       
  19.      
  20. function validate () {      
  21. var inputCode = document.getElementById("input1").value.toUpperCase();      
  22. var codeToUp=code.toUpperCase();  
  23. if(inputCode.length <=0) {      
  24.   alert("请输入验证码!");      
  25.   return false;      
  26. }      
  27. else if(inputCode != codeToUp ){      
  28.    alert("验证码输入错误!");      
  29.    createCode();      
  30.    return false;      
  31. }      
  32. else {      
  33.   alert("输入正确,输入的验证码为:"+inputCode);      
  34.   return true;      
  35. }      
  36.       
  37. }         

第五步:把四个文件放到一个文件夹中,运行login.htm文件,显示结果为:


原创粉丝点击