用JavaScript实现简单的验证码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/f120032777/article/details/73386120

                                用JavaScript实现简单的验证码

先展示一下最终的效果图



<!DOCTYPE html>

<html>


<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#box {
font-family: "微软雅黑";
width: 400px;
height: 200px;
padding: 20px;
background: skyblue;
margin: 0 auto;
border-radius: 30px;
margin-top: 100px;
}
h1{margin: 0;padding: 0;color: #fff;text-align: center;}
input {
float: left;
margin-top: 35px;
margin-left: 30px;
margin-right: 15px;
width: 150px;
height: 30px;

font-size: 20px;
text-indent: 1em;
}

span {
float: left;
width: 150px;
height: 32px;
margin-top: 35px;
background: #666;
letter-spacing: 5px;
color: #fff;
border:2px solid skyblue;
display: block;
}

button {
clear: both;
display: block;
width: 100px;
height: 50px;
background: skyblue;
color: #fff;
border-style: none;
font-size: 30px;
margin:100px auto;
font-weight:800;
}
</style>
<script type="text/javascript">
window.onload = function() {
var obtn = document.getElementsByTagName("button")[0];
var ospan = document.getElementsByTagName("span")[0];
var oinput = document.getElementsByTagName("input")[0];

var arr = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m"];                                                  //定义数组,输入验证码的组成元素
var arrlength = arr.length;
var str = '';

obtn.onclick = function() {

if(oinput.value == "") {                                                                //如果验证码为空,弹出提示“验证码不能为空”
alert('验证码不能为空! ')

else if(oinput.value != ospan.innerHTML) {                          //如果输入的验证码和所给的验证码不同,弹出提示“输入错误”
alert('输入错误! ')



} else {                                                                                          //如果输入的验证码和所给的验证码相同,弹出提示“输入正确”
alert('输入正确! ')


}


}



function number() {
for(var i = 0; i < 5; i++) {
var num = Math.floor(Math.random() * arrlength)
str += arr[num];



}

ospan.style.textIndent="1em"
ospan.style.lineHeight="30px"
ospan.innerHTML=str


}


number()


}
</script>
</head>


<body>
<div id="box">
<h1>请输入验证码</h1>
<input type="text"/>
<span></span>
<button>确&nbsp;认</button>


</div>
</body>


</html>

猜你喜欢

转载自blog.csdn.net/f120032777/article/details/73386120