給大家分享一個簡單的js驗證碼生成代碼
PS:該代碼依賴Jquery1.4版本以上
- 傳入元素 如productionVerificationCode(#\(("a")) 反回驗證碼的結果,#\)("a")元素寫入驗證碼
//----[生成數字加減乘法驗證碼](傳入寫入元素,返回驗證碼計算結果)
function productionVerificationCode(element) {
var code = 9999;
var ranColor = '#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).slice(-6); //隨機生成顏色
// alert(ranColor)
var ranColor2 = '#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).slice(-6);
var num1 = Math.floor(Math.random() * 100);
var num2 = Math.floor(Math.random() * 100);
//隨機算法
var tmparith = Math.floor(Math.random() * 3);
var $html = "";
switch(tmparith) {
case 1:
code = num1 + num2;
$html = num1 + ' + ' + num2 + ' = ?';
break;
case 2:
if(parseInt(num1) < parseInt(num2)) {
var tmpnum = num1;
num1 = num2;
num2 = tmpnum;
}
code = num1 - num2;
$html = num1 + ' - ' + num2 + ' = ?';
break;
default:
code = num1 * num2;
$html = num1 + ' × ' + num2 + ' = ?';
break;
}
element.val($html); //寫入驗證碼
if(element.hasClass("nocode")) {
element.removeClass("nocode");
element.addClass("code");
}
element.css('background', ranColor);
element.css('color', ranColor2);
return code;
}
//----[END][生成數字加減乘法驗證碼]