时间:2021-07-01 10:21:17 帮助过:12人阅读
本文实例讲述了jQuery实现input输入框获取焦点与失去焦点时提示的消失与显示功能。分享给大家供大家参考,具体如下:
最近都成为页面仔了,主要工作都放在了前段,以前总是写后台程序,对前端的一些技术 html,css,javascript ,虽然都懂一些,但要做出比较好看页面,还是有很大的差距的。最近就遇到了这样一个要求不是很高,但有点小清新风格的登录或注册页面,要求如下:
1. 在输入框中 如果没有内容,则显示提示:比如"请输入用户名"
2. 如果输入框获得焦点,则隐藏提示
3. 如果输入框失去焦点,并且输入框没有内容,则显示提示,如果有内容,则隐藏提示。
4. 采用 Jquery 1.7.2
在搜索了资料之后,发现通过label, input 并结合javascript 结合来实现,因为 label 有一个 for 属性,并指向input 的id ,这样,只要点击 label ,input 输入框就能获取焦点.一旦获取焦点就响应Javascript事件。隐藏label. 同样在失去焦点的时候,也触发事件,判断输入框是否有内容,来确定是否显示提示。整个效果如下:
获取焦点后
代码如下:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>www.gxlcms.com jQuery input焦点与提示文字</title>
- <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
- <script type="text/javascript">
- $(document).ready(function(){
- $("#loginform .input_txt").each(function(){
- var thisVal=$(this).val();
- //判断文本框的值是否为空,有值的情况就隐藏提示语,没有值就显示
- if(thisVal!=""){
- $(this).siblings("label").hide();
- }else{
- $(this).siblings("label").show();
- }
- //聚焦型输入框验证
- $(this).focus(function(){
- $(this).siblings("label").hide();
- }).blur(function(){
- var val=$(this).val();
- if(val!=""){
- $(this).siblings("label").hide();
- }else{
- $(this).siblings("label").show();
- }
- });
- })
- })
- </script>
- <style type="text/css">
- form{width:400px;margin:10px auto;border:solid 1px #E0fEDE;background:#FCF9EF;padding:30px;box-shadow:0 1px 10px rgba(0,0,0,0.1) inset;}
- span{display:block;height:40px;position:relative;margin:20px 0;}
- label{position:absolute;float:left;line-height:40px;left:10px;color:#BCBCBC;cursor:text;}
- .input_txt{width:398px;border:solid 1px #ccc;box-shadow:0 1px 10px rgba(0,0,0,0.1) inset;height:38px;text-indent:10px;}
- .input_txt:focus{box-shadow:0 0 4px rgba(255,153,164,0.8);border:solid 1px #B00000;}
- .border_radius{border-radius:5px;color:#B00000;}
- </style>
- </head>
- <body>
- <form class="border_radius" id="loginform">
- www.gxlcms.com得到焦点时提示语消失
- <span>
- <label for="username">请输入账号</label>
- <input type="text" class="input_txt border_radius" id="username" />
- </span>
- <span>
- <label for="password">密码</label>
- <input type="text" class="input_txt border_radius" id="password" />
- </span>
- </form>
- </body>
- </html>
感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具 http://tools.jb51.net/code/HtmlJsRun测试上述代码运行效果。
更多关于jQuery相关内容感兴趣的读者可查看本站专题:《jQuery form操作技巧汇总》、《jQuery操作json数据技巧汇总》、《jQuery常用插件及用法总结》、《jQuery扩展技巧总结》、《jQuery表格(table)操作技巧汇总》及《jquery选择器用法总结》
希望本文所述对大家jQuery程序设计有所帮助。