使用随機數做一個簡單的驗證碼
1.Math.random(): 擷取0~1随機數
2.Math.random()*num: 代表 取一個> = 0 且 小于 num 的數
3.一般會在前面 加上一個 Math.floor() 這個代表的是取整數
下面為這個驗證碼的代碼style樣式
<style>
.p1{
width: 150px;
height: 80px;
line-height: 80px;
text-align: center;
font-size: 33px;
font-family:Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
}
.sp1:hover{
cursor: pointer;
user-select: none;/* 禁止複制 */
}
.p2{
color: red;
display: none;
}
</style>
html部分
<i><p class="p1"></p></i>
<form action="">
<!-- placeholder 占位符 提示使用者輸入的資訊内容 不影響正常輸入 disabled 禁止輸入 -->
<!-- autocomplete 對使用者輸入的東西進行記憶 下次輸入進行彈出 off關閉 on開啟此功能 -->
<input type="text" id="user" placeholder="請輸入你的賬号" autocomplete="on" maxlength="6">
<!-- lable起提示作用 label中的for的值和input中id的值一樣,這樣就形成一種關聯,選中label就選中input -->
<label class="sp1" for="user">确認</label>
</form>
<p class="p2">請勿輸入非數字字母以及下劃線的東西</p>
Javascript部分
<script>
var p1 = document.getElementsByTagName('p')[0];
var sp1 = document.getElementsByClassName('sp1')[0];
var sp2 = document.getElementsByClassName('p2')[0];
var str = '1234567890ABCDEFGHIJKLMNOPGRSTUVWXYZ_';
var i = 1;
function chux() {
var yzm = '';
for (var i = 0; i < 6; i++) {
yzm += str.charAt(Math.floor(Math.random() * 2));
}
console.log(yzm);
p1.innerHTML = yzm;
};
chux();
p1.onclick = chux; //正則判斷一下 有沒有非數字和下劃線以外的東西 可要可不要
user.oninput = function () {
if (/[^\w]+/.test(user.value) == true) {
sp2.style.display = 'block'
} else {
sp2.style.display = 'none'
}
} s
p1.onclick = function () {
console.log(user.value);
console.log(p1.innerHTML);
if ((user.value).toUpperCase() == p1.innerHTML) {
window.location.href="https://baike.baidu.com/item/%E5%8E%89%E5%AE%B3/32409?fr=aladdin" target="_blank" rel="external nofollow" ;
}else if(user.value ===''){
alert('請輸入東西鴨');
} else {
if (i >= 3) {
chux();
alert('輸入錯誤已達到三次 驗證碼已經重新生成');
user.value = ''; i = 0
} else {
alert('輸入錯誤'); i++;
}
}
}