欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jquery文本框中的事件应用以输入邮箱为例

程序员文章站 2023-11-09 22:44:46
文本框中的事件应用:以输入邮箱为例,如图:   代码如下: . 代码如下:

文本框中的事件应用:以输入邮箱为例,如图:
jquery文本框中的事件应用以输入邮箱为例 
代码如下:

. 代码如下:


<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "https://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>jquery文本框中的事件应用</title>
<style type="text/css">
body{ font-size:13px;}
/*元素初始化样式*/
.pinit{ width:390px; height:55px; line-height:55px; padding-left:20px;}
.txtinit{ border:solid 1px #666; padding:3px; background-image:url('images/bg_email_input.gif');}
.spninit{ width:179px; height:40px; line-height:40px; float:right; margin-top:8px; padding-left:10px; background-repeat:no-repeat;}
/*元素丢失焦点样式*/
.pblur{ background-color:#feeec2;}
.txtblur{ border:solid 1px #666; padding:3px; background-image:url('images/bg_email_input2.gif');}
.spnblur{ background-image:url('images/bg_email_wrong.gif');}
.pfocu{ background-color:#edffd5;} /*p获取焦点样式*/
.spnsucc{ background-image:url('images/pic_email_ok.gif'); margin-top:20px;} /*验证成功时span样式*/
</style>
<script src="scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script src="scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#txtemail").trigger("focus"); //默认时文本框获得焦点
$("#txtemail").focus(function () { //文本框获取焦点事件
$(this).removeclass("txtblur").addclass("txtinit");
$("#email").removeclass("pblur").addclass("pfocu");
$("#spntip").removeclass("spnblur").removeclass("spnsucc").html("请输入您常用邮箱地址!");
});
$("#txtemail").blur(function () { //文本框丢失焦点事件
var vtxt = $("#txtemail").val();
if (vtxt.length == 0) { //文本框中是否输入了邮箱
$(this).removeclass("txtinit").addclass("txtblur");
$("# email").removeclass("pfocu").addclass("pblur");
$("#spntip").addclass("spnblur").html("邮箱地址不能为空!");
}
else { //检测邮箱格式是否正确
if (!chkemail(vtxt)) { //如果不正确
$(this).removeclass("txtinit").addclass("txtblur");
$("#email").removeclass("pfocu").addclass("pblur");
$("#spntip").addclass("spnblur").html("邮箱格式不正确!");
}
else { //如果正确
$(this).removeclass("txtblur").addclass("txtinit");
$("#email").removeclass("pfocu");
$("#spntip").removeclass("spnblur").addclass("spnsucc").html("");
}
}
});
/*验证邮箱格式是否正确 参数stremail,需要验证的邮箱*/
function chkemail(stremail) {
var vchk = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if (!vchk.test(stremail)) {
return false;
}
else {
return true;
}
}
});
</script>
</head>
<body>
<form id="form1" action="#">
<p id="email" class="pinit">邮箱:
<span id="spntip" class="spninit"></span>
<input type="text" id="txtemail" class="txtinit" />
</p>
</form>
</body>
</html>