HTML
<div class="box"> <div class="code" id="checkCode">{{nowCode}}</div> <a href="###" @click="changeCode">看不清,换一张</a> <input type="text" placeholder="请输入验证码" v-model="inputCode"> <button id="subBtn" @click="isLegalCode">验证</button> </div>
CSS
.box { width:300px; height:150px; border:1px solid; margin:30px auto; position:relative; } .code { width:120px; height:40px; background-color:#D6E3BC; border:2px solid; text-align:center; font-size:24px; line-height:40px; position:absolute; top:20px; left:20px; letter-spacing:3px; } a { position:absolute; left:160px; top:30px; color:green; } input { width:180px; height:20px; top:90px; left:20px; position:absolute; } button { width:50px; height:26px; position:absolute; top:90px; right:26px; background-color:green; color:#fff; border:1px solid gray; }
JS
// 生成验证码 createCode () { let codeLength = 6; // 验证码长度 let codeChars = 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', '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'); //验证码要随机挑选的字符 for (var i = 0; i < codeLength; i++) { let charIndex = Math.floor(Math.random() * 52); // 随机产生0-52之间的整数 this.nowCode += codeChars[charIndex]; } }, // 切换验证码 changeCode() { this.createCode(); }, // 校验验证码 isLegalCode() { if (this.inputCode == this.nowCode) { alert("验证码正确!"); } else { alert("验证码不正确,请重试!"); } }