js学习总结----字符串和Math综合应用-验证码(4位)
具体代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body,div,ul,li{
margin:0;
padding: 0;
font-family: Arial;
font-size:12px;
-webkit-user-select:none;
}
#code{
width:100px;
height:50px;
line-height: 50px;
text-align:center;
border:1px solid #ff0000;
cursor:pointer;
top:50%;
left:50%;
position:absolute;
margin-left:-50px;
margin-top:-25px;
letter-spacing: 3px
}
</style>
</head>
<body>
<div id='code'>xf2d</div>
<script type='text/javascript'>
//设置随机获取的范围
var codeStr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
//0-61索引,我只需要随机生成4个索引,然后通过charAt就可以获取到字符了
var oDiv = document.getElementById('code');
//获取随机数
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 ran = getRandom(0,61)
str +=codeStr.charAt(ran);
}
oDiv.innerHTML = str;
}
getCode();
oDiv.onclick = function(){
getCode();
}
</script>
</body>
</html>

浙公网安备 33010602011771号