<span id="code"></span>
<button id="btn">获取验证码</button>
<script>
//给btn绑定事件
btn.onclick = function () {
var str = "";
var num = null;
//获取4个随机数
for(var i = 0; i < 4; i++){
num = parseInt(Math.random() * 74 + 48);
//判断num是否合格
if(num >= 48 && num <= 57 || num >= 65 && num <= 90 || num >= 97 && num <= 122){
str += String.fromCharCode(num);
}else{
i--;
}
}
code.innerHTML = str;
code.style.color = randomColor();
}
//随机颜色
function randomColor(){
var str = "0123456789abcdf";
var color ="#";
for(var i = 0; i < 6; i++){
color += str[parseInt(Math.random() * 16)];
}
return color;
}