1 <!DOCTYPE html>
2 <html>
3
4 <head>
5 <meta charset="UTF-8">
6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 <meta http-equiv="X-UA-Compatible" content="ie=edge">
8
9 <title>前端验证码功能</title>
10 <style>
11 *{
12 margin: 0;
13 padding: 0;
14 }
15 body{
16 background: rgba(0, 0, 0, .1);
17 /* background: #061227; */
18 }
19 form{
20 width: 600px;
21 margin: 100px auto;
22 }
23 .box{
24 height: 40px;
25 line-height: 40px;
26 }
27 .tip{
28 float: left;
29 }
30 input{
31 float: left;
32 width: 200px;
33 height: 30px;
34 padding: 3px 10px;
35 line-height: 30px;
36 }
37 #identify{
38 float: left;
39 width: 100px;
40 height: 40px;
41 line-height: 40px;
42 font-weight: bold;
43 text-align: center;
44 letter-spacing: 2px;
45 background: #365c64;
46 color: #fff;
47 border-radius: 5px;
48 margin: 0 10px;
49 }
50 .btn{
51 margin: 25px auto;
52 }
53 .btn button{
54 width: 200px;
55 height: 36px;
56 line-height: 36px;
57 background: #409eff;
58 border-radius: 5px;
59 border: 0;
60 color: #fff;
61 }
62 </style>
63 </head>
64
65 <body>
66 <form action="">
67 <div class="box">
68 <span class="tip">验证码:</span>
69 <input type="text" id="text" value="" placeholder="请输入验证码" autocomplete="off">
70 <span id="identify" onclick="generatedCode()"></span>
71 <a href="javascript:void(0)" onclick="generatedCode()">看不清,换一张</a>
72 </div>
73 <div class="btn"><button onclick="checkCode()">验证</button></div>
74 </form>
75 </body>
76 <script>
77 generatedCode();
78 // 随机生成验证码
79 function generatedCode() {
80 var code1 = "";//生成的验证码
81 var 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\'];
82 for (let i = 0; i < 4; i++) {
83 var index = Math.floor(Math.random() * 36);//随机0-35
84 code1 += array[index];
85 document.getElementById("identify").innerHTML = code1;
86 }
87 console.log("二维码是:",code1)
88 };
89 // 验证用户输入
90 function checkCode() {
91 var code2 = document.getElementById("identify").innerHTML;//获取当前生成的验证码
92 code2 = code2.toUpperCase();
93
94 var code3 = document.getElementById("text").value; //客户输入的验证码
95 code3 = code3.toUpperCase();//把客户输入的验证码转换为大写
96 console.log("生成的二维码是:"+ code2 +"\n用户输入的验证码是:"+ code3)
97
98 if (code2 === code3) {
99 alert("恭喜验证成功");
100 // window.open(\'http://www.baidu.com\');
101 } else {
102 alert("输入的验证码不正确");
103 code3 = "";//清空用户输入
104 }
105 }
106 </script>
107 </html>