1. 程式人生 > >javascript實現動態驗證碼功能

javascript實現動態驗證碼功能


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<dl class="admin_login">
    <form action="#" method="post">
        <input type='hidden' name='codes' id='codes'>
        <dd class="user_icon">
            <input type
="text" placeholder="賬號" name="name" class="login_txtbx"/> </dd> <dd class="pwd_icon"> <input type="password" placeholder="密碼" name="paws" class="login_txtbx"/> </dd> <dd class="val_icon"> <div class="checkcode"> <input
type="text" id="J_codetext" name='code' placeholder="驗證碼" maxlength="4" class="login_txtbx"> <canvas class="J_codeimg" id="myCanvas" onclick="createCode()">對不起,您的瀏覽器不支援canvas,請下載最新版瀏覽器!</canvas> </div> <input type="button" value="更換驗證碼" class
="ver_btn" onClick="validate();"> </dd> <dd> <input type="submit" value="立即登陸" class="submit_btn"/> </dd> </form> </dl> </body> <script type=text/javascript> $(document).ready(function() {
//驗證碼 createCode(); }); //生成畫布 function showCheck(a){ var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.clearRect(0,0,1000,1000); ctx.font = "80px 'Microsoft Yahei'"; ctx.fillText(a,0,100); ctx.fillStyle = "white"; } //生成驗證碼的文字 var code ; function createCode(){ code = ""; var codeLength = 4; var selectChar = new Array(1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f','g','h','j','k','l','m','n','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z'); for(var i=0;i<codeLength;i++) { var charIndex = Math.floor(Math.random()*60); code +=selectChar[charIndex]; } if(code.length != codeLength){ createCode(); } showCheck(code); document.getElementById("codes").value=code; } //驗證碼較驗 function validate () { var inputCode = document.getElementById("J_codetext").value.toUpperCase(); var codeToUp=code.toUpperCase(); if(inputCode.length <=0) { document.getElementById("J_codetext").setAttribute("placeholder","請輸入驗證碼 "); createCode(); return false; } else if(inputCode != codeToUp ){ document.getElementById("J_codetext").value=""; document.getElementById("J_codetext").setAttribute("placeholder","請輸入正確的驗證碼"); createCode(); return false; } else { window.open(document.getElementById("J_down").getAttribute("data-link")); document.getElementById("J_codetext").value=""; createCode(); return true; } } </script> </html>