闲来无趣,写了个简单的JavaScript验证码

.

.

.

.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>JavaScript 验证码</title>
<script type="text/javascript" >
var code = ""; //验证码
//生成验证码
function createCode(){
	var num = 4; //验证码位数
	var codeList = new Array(1,2,3,4,5,6,7,8,9,0,'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'); //验证码内容
	//循环获取每一位验证码
		for(var i = 0; i < num; i++){
			//随机数 * 验证码候选元素数量 = 候选元素数组下标
			code += codeList[Math.floor(Math.random() * codeList.length)];
		}
		document.getElementById("txtCode").value = code;
}

//校验用户输入的验证码是否正确
function checkCode(){
	if(document.getElementById("inputCode").value == code)
		alert("验证码输入正确!");
	else
		alert("验证码填写错误!");
		code = "";
	createCode(); //生成新的验证码
}
</script>
</head>

<body onload="createCode()">
请输入验证码:<input id="inputCode" type="text" /><input id="txtCode" type="text" readonly /><input name="btnCheck" type="button" value="验证" onclick="checkCode()" />
</body>
</html>

原文地址:https://www.cnblogs.com/0xcafebabe/p/2103598.html