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 >