四位验证码

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>四个随机数</title>
<style>
#dd{
display: inline-block;
100px;
height: 20px;
background-color: aqua;
position: relative;
top:5px;
}
</style>
</head>

<body>
<form action="#">
账号:<input type = "text"><br><br>
密码:<input type = "password"><br><br>
验证码:<input type = "text" id ="YZM">
<div id = "dd"></div>
<button onClick="yzm()">看不清</button><br>
<input type = "button" value = "登录" onClick="isTrue()"><br><!--点击登录按钮,跳转登录判断方法-->
<span id = "info" style = "color:red"></span><!--错误显示,通过id显示错误以及正确信息-->
</form>
</body>
</html>
<script type = "text/javascript">
window.onload = yzm;
var str = "";
function yzm(){
str = "";
var arr = ["1","2","3","4","a","s","d"];//验证码表
for(var i = 0;i< 4;i++){//循环四次,因为是4位验证码
var xiabiao = parseInt(Math.random()*arr.length);//获取验证码字符的数组长度,作为随机数生成的数的范围
str = str + arr[xiabiao];//将得到的字符串长度作为数组的下标

}
document.getElementById("dd").innerHTML = str;//将获得的字符串给非标单元素赋值
console.log(str);
}
function isTrue(){
var userStr = document.getElementById("YZM").value;//获得用户手动输入的验证码
if(userStr == str){
document.getElementById("info").innerHTML = "验证码正确";
}else{
document.getElementById("info").innerHTML = "验证码错误";
}
}
</script>

原文地址:https://www.cnblogs.com/loveMis/p/8252564.html