JavaScript使用Math.random()生成簡單的驗證碼
更新時間:2019年01月21日 15:45:28 作者:muzidigbig
今天小編就為大家分享一篇關于JavaScript使用Math.random()生成簡單的驗證碼,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
第一種:單純的純數(shù)字驗證碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js驗證碼</title>
</head>
<body>
<div class="yzm" style="width: 20%;height: 300px;text-align: center;background-color: pink;line-height: 200px;"></div>
</body>
</html>
<script>
window.onload = function () {
var yzm=document.querySelector(".yzm");
//頁面一加載完成就生成隨機數(shù)調(diào)用rand()
yzm.innerHTML=rand(5);
//點擊切換隨機碼
yzm.onclick=function() {
var num = rand(5);
this.innerHTML = num;
};
//生成隨機碼
function rand(number){
//用來存儲產(chǎn)生的隨機數(shù)
var num="";
for(var i=0;i<number;i++){
num+=Math.floor(Math.random()*10)
}
return num;
}
}
</script>
第二種:輸入的驗證碼與生成的驗證碼進行校驗(數(shù)字與字母相結合)
<html>
<head>
<meta charset="UTF-8">
<title>驗證碼</title>
<style type="text/css">
#code
{
font-family:Arial;
font-style:italic;
font-weight:bold;
border:0;
letter-spacing:2px;
color:blue;
}
</style>
</head>
<body>
<div>
<input type = "text" id = "input"/>
<input type = "button" id="code" onclick="createCode()"/>
<input type = "button" value = "驗證" onclick = "validate()"/>
</div>
</body>
</html>
<script>
var code ; //在全局定義驗證碼
var number = 5;//驗證碼生成的個數(shù)
var checkCode = document.getElementById("code");
//產(chǎn)生驗證碼(頁面一加載就生成)
window.onload = function (){
createCode();
};
//產(chǎn)生驗證碼(輸入錯誤的時候刷新驗證碼,函數(shù)調(diào)用)
function createCode(){
code = "";
var codeLength = number;//驗證碼的長度
// var checkCode = document.getElementById("code");
var random = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R',
'S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',
's','t','u','v','w','x','y','z'];//隨機數(shù)
for(var i = 0; i < codeLength; i++) {//循環(huán)操作
var index = Math.floor(Math.random()*random.length);//取得隨機數(shù)的索引(random.length)
code += random[index];//根據(jù)索引取得隨機數(shù)加到code上
}
checkCode.value = code;//把code值賦給驗證碼
}
//校驗驗證碼
function validate(){
var inputCode = document.getElementById("input").value.toUpperCase(); //取得輸入的驗證碼并轉化為大寫
if(inputCode.length <= 0) { //若輸入的驗證碼長度為0
alert("請輸入驗證碼!"); //則彈出請輸入驗證碼
} else if(inputCode != code.toUpperCase() ) { //將隨機產(chǎn)生的驗證碼轉化為大寫,若輸入的驗證碼與產(chǎn)生的驗證碼不一致時
alert("驗證碼輸入錯誤!@_@"); //則彈出驗證碼輸入錯誤
createCode();//刷新驗證碼
document.getElementById("input").value = "";//清空文本框
}
else { //輸入正確時
alert("正確^-^"); //彈出^-^
}
}
</script>
若有不足請多多指教!希望給您帶來幫助!
總結
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內(nèi)容請查看下面相關鏈接
相關文章
教你巧用?import.meta?實現(xiàn)熱更新的問題
import.meta?是一個給?JavaScript?模塊暴露特定上下文的元數(shù)據(jù)屬性的對象,它包含了這個模塊的信息,這篇文章主要介紹了巧用?import.meta?實現(xiàn)熱更新的問題,需要的朋友可以參考下2022-04-04
promise中reject和catch處理上區(qū)別對比分析
在 Promise 中,reject?和?catch?是處理異步操作失敗的兩種方式,本文給大家介紹promise中reject和catch處理上區(qū)別對比分析,感興趣的朋友跟隨小編一起看看吧2024-07-07

