驗證碼通用模組 javascript版

來源:互聯網
上載者:User
CheckCode.js

 

 

 

/*
getCheckCode(elementId)產生驗證碼,將在Id為elementId的HTML元素的innerHTML中寫入HTML圖片源碼
CheckCodeOK("使用者輸入的驗證碼") 返回true,即為通過驗證
*/
var imgFolderPath="images/CheckCode/";  //存放路徑
var fileExt=".gif";  //副檔名,要加上圓點的
var imgWidth=15;  //映像寬
var imgHeight=20;  //映像高
var imgFileName=new Array(10); //檔案名稱,不要加副檔名
var CheckCodeStr="";  //存放當前的驗證碼,可以用來比較
imgFileName[0]="0";
imgFileName[1]="1";
imgFileName[2]="2";
imgFileName[3]="3";
imgFileName[4]="4";
imgFileName[5]="5";
imgFileName[6]="6";
imgFileName[7]="7";
imgFileName[8]="8";
imgFileName[9]="9";

function getCheckCode(elementId)  //產生驗證碼,將在Id為elementId的HTML元素的innerHTML中寫入HTML圖片源碼
{
    htmlStr="";
    CheckCodeStr=""; //清空原驗證碼
    for (i=0;i<4;i++)
    {
        num=Math.round(Math.random()*10-0.5);
        CheckCodeStr+=num.toString();
        filePath=imgFolderPath+imgFileName[num]+fileExt;
        htmlStr+="<img border=0 width=@width@ height=@height@ alt='點擊更換一組驗證碼' src='@src@' onclick='getCheckCode("@elementid@")' style='cursor:hand'>";
        htmlStr=htmlStr.replace("@width@",imgWidth);
        htmlStr=htmlStr.replace("@height@",imgHeight);
        htmlStr=htmlStr.replace("@src@",filePath);
        htmlStr=htmlStr.replace("@elementid@",elementId);
    }
    document.getElementById(elementId).innerHTML=htmlStr;
}

function CheckCodeOK(str)
{
    if (str==CheckCodeStr)
    {
        return true;
    }
    else
    {
        return false;
    }
}

 

test.html

<script language=javascript src=CheckCode.js></script>

<body onload="getCheckCode('CheckCodeImg')">

<div id="CheckCodeImg"> <!--驗證碼圖片出現在此處--></div>

<input type=button value="Click Me" onclick="getCheckCode('CheckCodeImg')"><br><br>
<input type=text name="CheckCode">
<input type=button value="Check" onclick="if (CheckCodeOK(document.getElementById('CheckCode').value)){alert('OK');}else {alert('error')}">

</body>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.