实现原理
利用javascript的Math对象的random和round函数随机生成大小写字母和数字的组合字符串,
然后再以不区分大小写为前提进行检验。
HTML代码
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/checkCode.js"></script>
<title>CheckCode</title>
<style type="text/css">
#code {
width: 80px;
height: 30px;
color: #000079;
font-size: 16px;
cursor: pointer;
background: #BEBEBE;
text-align: center;
}
</style>
<script type = "text/javascript">
function createCode() {
$("#code").val(randomStr(true, 4, 6));
}
function validate() {
// 不区分大小写
var inputVal = $("#in的putVal").val().toUpperCase();
var code = $("#code").val().toUpperCase();
if (inputVal.length < 1) {
alert("请输入验证码!");
} else if (inputVal != code) {
alert("验证码输入错误,请重新输入~~");
$("#code").val(randomStr(true, 4, 6));
} else {
alert("验证码输入正确,过关~~"); //弹出^-^
}
}
</script>
</head>
<body>
<div>
<input type = "text" id = "inputVal"/>
<input type = "button" id="code" οnclick="createCode()"/>
<input type = "button" value = "验证" onclick = "validate()"/>
</div>
</body>
</html>
-------------------------------------------------------------------------------------------------------------------------------
javascript代码(checkCode.js)
/**
* 产生任意长度随机字母数字组合
* @parameter flg-是否任意长度
* @parameter min-任意长度最小位[固定位数]
* @parameter max-任意长度最大位
*/
function randomStr(flg,min,max) {
var str = "";
// 固定长度
var range = min;
// 大小写字母+数字,一共62个字符
var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
// 随机产生字符串的长度为min到max之间的任意一个数,包括min和max
if(flg){
range = Math.round(Math.random() * (max-min)) + min;
}
// 随机产生字符串
for(var i=0; i < range; i++) {
// 取字符串在字符数组【arr】里的位置(0到61)
pos = Math.round(Math.random() * (arr.length-1));
str += arr[pos];
}
return str;
}
知识点总结
1.Math:数学对象,提供对数据的数学计算。
2.Math.random(); 返回0和1间(包括0,不包括1)的一个随机数。
3.Math.round(n); 返回n四舍五入后整数的值。
用Math.round(Math.random());可均衡获取0到1的随机整数。
用Math.round(Math.random()*10);时,可基本均衡获取0到10的随机整数,其中获取最小值0和最大值10的几率少一半。