javascript实现动态验证码功能

来源:互联网 发布:网络管理结构的重要性 编辑:程序博客网 时间:2024/06/06 14:27
<!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>