纯JS实现的页面验证码-可自定义长度和验证码字符
生成验证码的函数
<script type="text/javascript"> var code; function createCode() { code = ""; var codeLength = 4; //验证码的长度 var checkCode = document.getElementById("checkCode"); var 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++) { var charNum = Math.floor(Math.random() * 52); code += codeChars[charNum]; } if(checkCode) { checkCode.className = "code"; checkCode.innerHTML = code; } } </script>
登录页面代码:
<body onload="createCode()"> <form id="form1" action="loginCheck.jsp" onsubmit="return validateCode()"> <div> <table border="0" cellspacing="5" cellpadding="5" > <tr> <td>用户名:</td> <td><input type="text" name="username" id="username"></td> <td></td> </tr> <tr> <td>密 码:</td> <td><input type="text" name="pwd" id="pwd"></td> <td></td> </tr> <tr> <td>验证码:</td> <td><input style="float:left;" type="text" id="inputCode" /></td> <td><div class="code" id="checkCode" onclick="createCode()" ></div><a href="#" onclick="createCode()">看不清换一张</a></td> </tr> <tr> <td></td> <td><input id="Button1" type="submit" value="确定" /></td> <td></td> </tr> </table> </div> </form> </body>
检验验证码是否输入和输入是否正确的validateCode()函数代码:
function validateCode() { var inputCode=document.getElementById("inputCode").value; if(inputCode.length <= 0) { alert("请输入验证码!"); return false; } else if(inputCode.toUpperCase() != code.toUpperCase()) { alert("验证码输入有误!"); createCode(); return false; } else { return true; } }
美化验证码CSS:
<style type="text/css"> .code { background:url(code_bg.jpg); font-family:Arial; font-style:italic; color:blue; font-size:18px; border:0; padding:2px 3px; letter-spacing:3px; font-weight:bolder; float:left; cursor:pointer; width:100px; height:18px; line-height:18px; text-align:center; vertical-align:middle; } a { text-decoration:none; font-size:12px; color:#288bc4; } a:hover { text-decoration:underline; } </style>
125jz网原创文章。发布者:江山如画,转载请注明出处:http://www.125jz.com/2767.html