<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
#box{
width: 180px;
height: 90px;
margin:100px auto;
border: 1px solid black;
position: relative;
}
#box #box_random{
width: 80px;
height: 50px;
font-size: 16px;
text-align: center;
line-height: 50px;
color: blue;
border: 1px solid red;
cursor: pointer;
margin: auto;
}
#box input{
position: absolute;
left: 10px;
top: 14px;
}
</style>
</head>
<body>
<div id="box">
<input type="button" value="刷新" onclick="ran_creat()">
<div id="box_random"></div>
</div>
</body>
<script>
//0-9 A-Z a-z对应的unicode是 48-57 65-90 97-122
function ranNum(min,max){
return function(){
// 利用闭包,等我们需要产生随机数在调用
return parseInt(Math.random()*(max-min+1)+min)
}
}
function ran_creat(){
// 即将产生在48-122区间的随机的一个unicode编码,未调用
var myUni = ranNum(48,122)
// 用来装四个符合[0-9 a-z A-Z]的unicode编码
var str = "";
var n = 0;
// 产生四个unicode放入arr数组中
while(true){
// 产生一个随机码
var num = myUni()
// 符合需求在48-57,65-90,97-122的随机数放入arr数组中,知道arr装满四个
if (num >= 48 && num <= 57 || num >= 65 && num <= 90 || num >= 97 && num <= 122){
var s = String.fromCharCode(num)
str += s ;
n++;
}
if(n==4)
break;
}
document.getElementById('box_random').innerHTML = str ;
}
ran_creat();//先调用一次,否则初始没有验证码
</script>
</html>