实现逻辑:
1、生成验证码 总共6位数 范围:0-9 a-f 随机生成 从0-9 、 a-f获取随机下标 2、 页面加载时,生成一次 点击看不清换一张时,生成一次 将生成的验证码与输入的验证码进行验证比对
<style type="text/css"> .code { height: 50px; } .code span { float: left; background: #cecece; line-height: 50px; height: 50px; width: 120px; text-align: center; } .code a { text-decoration: none; float: left; line-height: 50px; margin-left: 20px; } </style> <div class="box"> <div class="code"> <span id="check">23232</span> <a href="#" id="toggle">看不清换一张</a> </div> </div> <div class="input"> <label for="ipt">验证码:</label> <input type="text" id="ipt" /> </div> <button id="btn">确定</button> <script type="text/javascript"> var code = document.getElementById("check"); var ipt = document.getElementById("ipt"); var toggle = document.getElementById("toggle"); var btn = document.getElementById("btn"); function getCode() { var arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "e", 'f']; var str = ""; for (let i = 0; i < 6; i++) { str += arr[Math.floor(Math.random() * arr.length)]; } return str; } code.innerText = getCode(); toggle.onclick = function () { code.innerText = getCode(); } btn.onclick = function () { var code = document.getElementById("check").innerText; var checkcode = ipt.value; if (code != checkcode) { ipt.value = ""; alert("验证码输入错误!"); return; } alert("验证通过!") } </script>