因为公司项目的需求,学习了几天的JS,现将刚看到的JS获取验证码,并验证的全代码记录下来,方便大家学习!
1.获取本地自制的验证码:
<pre name="code" class="javascript"><html>
<head>
<style type="text/css">
.code{
background-image:url(111.jpg);
font-family:Arial;
font-style:italic;
color:green;
border:0;
padding:2px 3px;
letter-spacing:3px;
font-weight:bolder;
}
.unchanged {
border:0;
}
</style>
<script language="javascript" type="text/javascript">
var code ; //在全局 定义验证码
function createCode(){
code = "";
var codeLength = 4;//验证码的长度
var checkCode = document.getElementById("checkCode");
checkCode.value = "";
var selectChar = new Array(2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z');
for(var i=0;i<codeLength;i++) {
var charIndex = Math.floor(Math.random()*32);
code +=selectChar[charIndex];
}
if(code.length != codeLength){
createCode();
}
checkCode.value = code;
}
function validate () {
var inputCode = document.getElementById("input1").value.toUpperCase();
if(inputCode.length <=0) {
alert("请输入验证码!");
return false;
}
else if(inputCode != code ){
alert("验证码输入错误!");
createCode();
return false;
}
else {
alert("OK");
return true;
}
}
</script>
</head>
<body οnlοad="createCode();">
<input type="text" id="input1" />
<input type="text" id="checkCode" class="code" style="width: 55px" /> <a href="#" οnclick="createCode()">看不清楚</a><br /><br />
<center><input id="Button1" οnclick="validate();" type="button" value="确定" /></center>
<script></script>
</body>
</html>
2.获取网络验证码:
<html>
<head>
<script>
function myFunction(){
var element = document.getElementById("img_captcha");
var link = element.src ;
link = link.split("?")[0];
element.src=link+'?'+(new Date()).getTime();
}
</script>
<head>
<body>
<form class="login" method="post" action="login" id="login-form">
<p><span class="input-bg"><input type="text" name="username" id="userId" placeholder="邮箱" autocomplete="on" value=""/></span></p>
<p><span class="input-bg"><input type="password" name="password" id="passWord" placeholder="密码" /></span></p>
<p><span style="float:left;margin-right:12px;" class="input-bg">
<input type="text" name="captcha" id="captcha" placeholder="验证码" style="width:100px;" maxlength="4"//></span>
<img title="点击更换" style="cursor: pointer;" id="img_captcha" url="http://baige.aliapp.com/foodapp/yzm.php" src="http://baige.aliapp.com/foodapp/yzm.php"
onclick = "myFunction()"/>
</p>
<p class="btnpanel">
<input type="hidden" id="lt" name="lt" value="LT-1417766126rQMOlvHi6p5O0TwVZEH" />
<input type="hidden" id="captcha_i" name="captcha_i" value="568457" />
<input type="hidden" id="service" name="service" value="http://www.umeng.com/users/login_redirect" />
<input type="submit" value="登 录" class="submit" id="login-submit" accesskey="l"/>
<span>
<a href="http://www.umeng.com/users/password/new" class="forget">忘记密码?</a>
<a href="http://www.umeng.com/users/sign_up" class="reg">注册</a>
</span>
</p>
</form>
</body>
<html>