一个用js生成验证码的例子


嗯,今天展示一个简单的js生成验证码的例子吧,挺方便的,


html 如下:


  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <style type="text/css">
  6. .code {
  7. background: url(code_bg.jpg);
  8. font-family: Arial;
  9. font-style: italic;
  10. color: blue;
  11. font-size: 30px;
  12. border: 0;
  13. padding: 2px 3px;
  14. letter-spacing: 3px;
  15. font-weight: bolder;
  16. float: left;
  17. cursor: pointer;
  18. width: 150px;
  19. height: 60px;
  20. line-height: 60px;
  21. text-align: center;
  22. vertical-align: middle;
  23. }

  24. a {
  25. text-decoration: none;
  26. font-size: 12px;
  27. color: #288bc4;
  28. }

  29. a:hover {
  30. text-decoration: underline;
  31. }
  32. </style>
  33. <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  34. <script type="text/javascript">
  35. var code;
  36. function createCode() {
  37. code = "";
  38. var codeLength = 6; //验证码的长度
  39. var checkCode = document.getElementById("checkCode");
  40. var codeChars = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c',
  41. 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
  42. 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A',
  43. 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  44. 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'); //所有候选组成验证码的字符,当然也可以用中文的
  45. for (var i = 0; i < codeLength; i++) {
  46. var charNum = Math.floor(Math.random() * 52);
  47. code += codeChars[charNum];
  48. }
  49. if (checkCode) {
  50. checkCode.className = "code";
  51. checkCode.innerHTML = code;
  52. }
  53. }

  54. function validateCode() {

  55. var inputCode = document.getElementById("inputCode").value;
  56. if (inputCode.length <= 0) {
  57. alert("请输入验证码!");
  58. } else if (inputCode.toUpperCase() != code.toUpperCase()) {
  59. alert("验证码输入有误!");
  60. createCode();
  61. } else {
  62. alert("验证码正确!");
  63. }
  64. }
  65. </script>
  66. </head>
  67. <body onload="createCode()">
  68. <form id="form1" runat="server" onsubmit="validateCode()">
  69. <div>
  70. <table border="0" cellspacing="5" cellpadding="5">
  71. <tr>
  72. <td></td>
  73. <td>
  74. <div class="code" id="checkCode" onclick="createCode()"></div>
  75. </td>
  76. <td><a href="#" onclick="createCode()">看不清换一张</a></td>
  77. </tr>
  78. <tr>
  79. <td>验证码:</td>
  80. <td><input style="float:left;" type="text" id="inputCode" /></td>
  81. <td>请输入验证码</td>
  82. </tr>
  83. <tr>
  84. <td></td>
  85. <td><input id="Button1" onclick="validateCode()" type="button"
  86. value="确定" /></td>
  87. <td></td>
  88. </tr>
  89. </table>
  90. </div>
  91. </form>
  92. </body>
  93. </html>
评论已关闭