1. 程式人生 > >用JavaScript實現簡單的驗證碼

用JavaScript實現簡單的驗證碼

                                用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>