<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>验证码</title>
<style>
html,body,div{
margin: 0;
padding: 0;
}
#validate{
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -20px;
width: 100px;
height: 40px;
background: #f0f000;
font-size: 28px;
line-height: 40px;
text-align: center;
}
</style>
</head>
<body>
<div id="validate"></div>
<script>
//0-61个索引中随机生成四个索引数,通过charAt取到对应的字符
var codeStr ="abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXZY0123456789";
var validate = document.getElementById('validate');
function getRandom(n,m){
n = Number(n);
m = Number(m);
if(isNaN(n) || isNaN(m)){
return Math.random();
}
if(n>m){
var temp = n;
n = m;
m =temp;
}
return Math.round(Math.random()*(m-n)+n);
}
function getCode(){
var str='';
for (var i = 0; i < 4; i++) {
var random = getRandom(0,61);
str+=codeStr.charAt(random);
}
validate.innerHTML=str;
}
getCode();
validate.onclick = function(){
getCode();
}
</script>
</body>
</html>
详细信息可见: http://www.w3cfuns.com/blog-5441829-5407747.html