首页 > 技术文章 > 验证码的实现

bad-guy 2017-06-27 16:48 原文

我将验证码放在了登录界面,先来看一下效果吧

HTML部分:

验证码:<input class="easyui-textbox" id="inputCode" style="width: 100px">
<input type="text" id="checkCode" class="code" style="width:50px;">
<a href="#" onclick="lode()">看不清</a>

CSS部分:

<style>
.code{
background-image: url("skin/Images/005.jpg");
font-family: Arial;
font-style: italic;
color: red;
border:0;
padding: 2px 3px;
letter-spacing: 3px;
font-weight: bolder;
}
</style>

JavaScript部分:

<script type="text/javascript">
var code;
$(function(){
//初始化验证码方法
createCode();
})
/**
* 初始化验证码
*/
function createCode(){
//定义一个变量用来存储验证码
code="";
//定义一个变量用来确定验证码的长度
var codeLength=4;
//定义一个数组,验证码值从该数组中来取
var selectChar=new Array(1,2,3,4,5,6,7,8,9,'q','w','e','r','t','y','u','i','p','a','s','d','f','g','h','j','k','x','c','v','b','n','m');
//遍历验证码的长度
for(var i=0;i<codeLength;i++){
//随机生成一个数字,该数字即是数组的下标
var charIndex=Math.floor(Math.random()*32);
//通过下标取出数组中的元素放在验证码变量里,用+连接
code+=selectChar[charIndex];
}
//当验证码长度没达到固定长度则重新初始化验证码
if(code.length!=codeLength){
createCode();
}
//将循环得到的验证码值放在输入框里
$("#checkCode").val(code);
}


//看不清的时候则重新初始化验证码
function lode(){
createCode();
$("#inputCode").textbox('clear');
}

点击登录按钮时,则会触发login事件,登录之前首先需要判断验证码是否输入正确。
function login(){
//获取输入框里面的验证码
var inputCode=$("#inputCode").textbox("getValue");
//判断验证码是否符合长度
if(inputCode.length<=0){
showMessageCenter("请输入验证码!",160);
createCode();
return;
}
//判断验证码是否输入正确
if(inputCode!=code){
showMessageCenter("验证码输入错误!",160);
$("#inputCode").textbox('clear');
createCode();
return;
}
}

注意:这其中弹出框之类的都是封装好的js

/**
* 在浏览器中间显示一个会自动消失的提示框
* @param msg
* @param width
*/
function showMessageCenter(msg, width) {
$.messager.show({
msg: msg,
width: width,
height: 45,
showType: 'slide',
timeout: 2000,
align: 'center',
style: {
right: '',
bottom: ''
}
});
}

 

推荐阅读