第一种:单纯的纯数字验证码
<!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>
若有不足请多多指教!希望给您带来帮助!
总结