第一種:單純的純數字驗證碼
<!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"); //頁面一加載完成就生成隨機數調用rand() yzm.innerHTML=rand(5); //點擊切換隨機碼 yzm.onclick=function() { var num = rand(5); this.innerHTML = num; }; //生成隨機碼 function rand(number){ //用來存儲產生的隨機數 var num=""; for(var i=0;i<number;i++){ num+=Math.floor(Math.random()*10) } return num; } }</script>
第二種:輸入的驗證碼與生成的驗證碼進行校驗(數字與字母相結合)
<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;//驗證碼生成的個數 var checkCode = document.getElementById("code"); //產生驗證碼(頁面一加載就生成) window.onload = function (){ createCode(); }; //產生驗證碼(輸入錯誤的時候刷新驗證碼,函數調用) 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'];//隨機數 for(var i = 0; i < codeLength; i++) {//循環操作 var index = Math.floor(Math.random()*random.length);//取得隨機數的索引(random.length) code += random[index];//根據索引取得隨機數加到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() ) { //將隨機產生的驗證碼轉化為大寫,若輸入的驗證碼與產生的驗證碼不一致時 alert("驗證碼輸入錯誤!@_@"); //則彈出驗證碼輸入錯誤 createCode();//刷新驗證碼 document.getElementById("input").value = "";//清空文本框 } else { //輸入正確時 alert("正確^-^"); //彈出^-^ } }</script>
若有不足請多多指教!希望給您帶來幫助!
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對武林網的支持。如果你想了解更多相關內容請查看下面相關鏈接
新聞熱點
疑難解答