简单验证码
简单验证码实现,在实际开发中可能用不上,但是这种方法可以学习一下;下面是代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
function chkyzm(form){
if(form.yzm.value==""){
yzm1.innerHTML="<font color=#FF0000>请输入效验码!</font>";
}else{
alert("输入的验证码正确");
}
}
function yzm(form){
var num1=Math.round(Math.random()*10000000);
var num=num1.toString().substr(0,4);
document.write("<img name=codeimg src='yzm.php?num="+num+"'>");
form.yzm2.value=num;
}
function code(form){
var num1=Math.round(Math.random()*10000000);
var num=num1.toString().substr(0,4);
document.codeimg.src="yzm.php?num="+num;
form.yzm2.value=num;
}
</script>
<table>
<form id="register" name="register" action="#" method="post">
<tr>
<td><div align="right">验证码:</div></td>
<td>
<input id="yzm" type="text" name="yzm" onBlur="javascript:chkyzm(register)" onMouseOver="this.style.backgroundColor='blue'" onMouseOut="this.style.backgroundColor='yellow'"/>
<input name="yzm2" type="hidden" value="" />
</td>
<td align="center" valign="middle"><script>yzm(register)</script></td>
<td><a href="javascript:code(register)">看不清</a></td>
<td><div id="yzm1"><font color="#999999">输入验证码</font></div></td>
<td><input type="submit" value="提交"/> <input type="reset" value="重写" /></td>
</tr>
</form>
</table>
</body>
</html>
知识点
引用JavaScript的方式:
JavaScript:函数名(参数)
<script>函数名(参数)</script>
onblur事件会在对象失去焦点时发生。www.w3school.com.cn/jsref/event_onblur.asp
onmouseover事件会在鼠标指针移动到指定的对象上时发生。www.w3school.com.cn/jsref/event_onmouseover.asp
onmouseout属性在鼠标指针移动到元素外时触发。www.w3school.com.cn/tags/event_onmouseout.asp
下面是使用GD库函数生成验证码背景和干扰代码:
header ( "Content-type: text/html; charset=UTF-8" ); //设置文件编码格式
srand((double)microtime()*1000000); //生成随机数
$im=imagecreate(65,35); //创建画布
$black=imagecolorallocate($im,0,0,0); //定义背景
$white=imagecolorallocate($im,255,255,255); //定义背景
$gray=imagecolorallocate($im,200,200,200); //定义背景
imagefill($im,0,0,$gray); //填充颜色
for($i=0;$i<4;$i++){ //定义4位随机数
$str=mt_rand(3,20); //定义随机字符所在位置的的Y坐标
$size=mt_rand(5,8); //定义随机字符的字体
$authnum=substr($_GET['num'],$i,1); //获取超级链接中传递的验证码
imagestring($im,$size,(2+$i*15),$str,$authnum,imagecolorallocate($im,rand(0,130),rand(0,130),rand(0,130)));
} //水平输出字符串
for($i=0;$i<200;$i++){ //执行for循环,为验证码添加模糊背景;生成干扰线
$randcolor=imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255)); //创建背景;定义干扰线颜色
imagesetpixel($im,rand()%70,rand()%30,$randcolor); //绘制单一元素;生成干扰线
}
imagepng($im); //生成png图像
imagedestroy($im); //销毁图像
?>
JavaScript事件参考手册www.w3school.com.cn/jsref/jsref_events.asp

浙公网安备 33010602011771号