html部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="验证码.js"></script>
<link rel="stylesheet" href="yanzhnegma.css">
</head>
<body>
<div>
<input type = "text" id = "input" value="" />
<input type = "button" class="button" id="code" onclick="createCode()"/>
<input type = "button" class="button" value = "验证" onclick = "validate()"/>
</div>
</body>
</html>
css部分
#code{
font-family:Arial;
font-style:italic;
font-weight:bold;
border:0;
letter-spacing:2px;
color:blue;
}
.button{
width:100px;
height:50px;
color: blue;
background-color: aqua;
border: 0px solid grey;
border-radius: 15px;
outline: none;
}
js部分:
//设置一个全局的变量,便于保存验证码
var code;
function createCode(){
//首先默认code为空字符串
code = '';
//设置长度,这里看需求,我这里设置了4
var codeLength = 4;
var codeV = document.getElementById('code');
//设置随机字符
var random = new Array(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');
//循环codeLength 我设置的4就是循环4次
for(var i = 0; i < codeLength; i++){
//设置随机数范围,这设置为0 ~ 36
var index = Math.floor(Math.random()*36);
//字符串拼接 将每次随机的字符 进行拼接
code += random[index];
}
//将拼接好的字符串赋值给展示的Value
codeV.value = code;
}
//下面就是判断是否== 的代码,无需解释
function validate(){
var oValue = document.getElementById('input').value.toUpperCase();
if(oValue ==0){
alert('请输入验证码');
}else if(oValue != code){
alert('验证码不正确,请重新输入');
oValue = ' ';
createCode();
}else{
window.open('http://www.baidu.com','_self');
}
}
//设置此处的原因是每次进入界面展示一个随机的验证码,不设置则为空
window.onload = function (){
createCode();
}