<!-- 页面加载的时候获取验证码 -->
<body onload="createCode()">
<main>
<input type="text" id="input1"/>
<input disabled type="text" id="checkCode" class="code"/>
<span onclick="createCode()">看不清楚
</span>
<input id="Button1" onclick="validate()" type="button" value="确定"/>
</main>
</body>
<script>
//在全局定义验证码信息以及获取dom节点
var code , //验证码
codeLength = 4,//验证码的长度;
checkCode = document.getElementById("checkCode"), //验证码容器
inputCodeEle = document.getElementById("input1"), //验证码判断表单
selectChar = [2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','J','K','L','M',
'N','P','Q','R','S','T','U','V','W','X','Y','Z']; //验证码内容
//生成验证码
function createCode(){
code = "";
checkCode.value = "";
for(var i=0;i<codeLength;i++) {
//随机生成验证码
var charIndex = Math.floor(Math.random()*32);
code +=selectChar[charIndex];
}
if(code.length != codeLength) createCode();
checkCode.value = code;
}
//验证码验证
function validate(){
//toUpperCase 如果是小写的,转化为大写的
var inputCode = inputCodeEle.value.toUpperCase();
//输入为空的时候
if(inputCode.length <=0){
alert("请输入验证码!");
return false; //为防止验证码错误的情况下出现表单提交
//输入错误的时候
}else if(inputCode != code ){
alert("验证码输入错误!");
createCode();
return false;
//输入成功的时候
}else{
alert("OK");
return true;
}
}
</script>