<!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>
#code{
width: 100px;
height: 30px;
line-height: 30px;
text-align: center;
border: 1px solid #333;
}
button{
margin-top:30px;
}
</style>
</head>
<body>
<div id="code"></div>
<button id="btn">获取验证码</button>
</body>
</html>
<script>
//点击button,出现四位随机数
//验证码长度:4位
//组合:数字(0-9),字母(大小写)
var code=document.getElementById("code");//获取验证码输入框
var btn=document.getElementById("btn");//获取按钮
var str="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890"
function getCode(str){
//转大写,用random
var res="";
for(var i=0;i<4;i++){
//四舍五入 随机的 长度内的
var index=Math.round(Math.random()*(str.length-1));
res+=str[index];
}
return res;
}
code.innerHTML=getCode(str)//默认给一个
btn.onclick=function(){
code.innerHTML=getCode(str)
}
</script>
---------------------------------------while也能实现
<!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>
#code {
width: 100px;
height: 30px;
line-height: 30px;
text-align: center;
border: 1px solid #333;
}
button {
margin-top: 30px;
}
</style>
</head>
<body>
<div id="code"></div>
<button id="btn">获取验证码</button>
</body>
</html>
<script>
var code=document.getElementById("code");
var btn=document.getElementById("btn");
var str="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
function getCode(){
var res='';
while(res.length<4){
var index=Math.round(Math.random()*(str.length-1));
if(res.indexOf(str[index])==-1){//==-1说明没有此项,就加上
res+=str[index];
}
}return res;
}
code.innerHTML=getCode(str);
btn.onclick=function(){
code.innerHTML=getCode(str);
}
</script>
11-13
2313
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-08
1404
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)