验证码功能
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> #box { width: 150px; height: 50px; background: #A9A9A9; line-height: 50px; text-align: center; color: white; } #a { display: inline-block; float: left; position: relative; top: -35px; left: 150px; cursor: pointer; } input { width: 80px; } </style> <script type="text/javascript"> /* 需求 生成一个6位数的随机数 拿到6位数的随机数在文本框比对,如果对则提示ok 否则提示比对不通过 */ window.onload = function() { //获取要使用的元素 var box = document.getElementById("box"); var a = document.getElementById("a"); var ipt = document.getElementsByTagName("input")[0]; var btn = document.getElementsByTagName("button")[0]; var str = ""; //定义一个数组用来保存随机的数 var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, "a", "b", "c", "d", "e", "f", "g"]; function myFun(){ str = ""; for (var i = 0; i < 6; i++) { var res = Math.round(Math.random() * (15 - 0) + 0); //当前是生成的随机数 str += arr[res]; box.innerText = str; } return str; } myFun(); a.onclick = function() { myFun(); } btn.onclick = function(){ if(box.innerText == ipt.value){ console.log("yes"); }else if(ipt.value.length>6){ console.log("过长"); ipt.value = ""; } else{ ipt.value = ""; console.log("验证码错误"); } } } </script> </head> <body> <div id="box"></div> <span id="a">看不清换一张</span> <br> <span>验证码</span> <input type="text" value=""> <br> <button type="button">确定</button> </body> </html>