jquery实现文本框默认值功能

我只是一个虾纸丫 提交于 2019-11-27 05:50:52

jquery实现文本框默认值功能

文本框是页面中使用最为频繁的表单元素之一,熟练地做一个智能的文本框可不是你想象的那么简单,下面就让源码来告诉你如何写好文本框的默认值。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

 <head>

   <title>XXX</title>

   <meta http-equiv="content-type" content="text/html;charset=UTF-8">

       <scriptlanguage="JavaScript" src="js/jquery-1.3.1.js"></script>

       <styletype="text/css">

                    div,span{

                         width: 140px;

                         height: 140px;

                         margin: 20px;

                         background: #9999CC;

                         border: #000 1px solid;

                            float:left;

                         font-size: 17px;

                         font-family:Roman;

                     }

                     div.mini{

                         width: 30px;

                         height: 30px;

                         background:#CC66FF;

                         border: #000 1px solid;

                         font-size: 12px;

                         font-family:Roman;

                     }

        </style>

       </head>

       <body>

              <!--value默认值,通过this.defaultValue来访问-->

               <input type="text" value="用户邮箱/手机号/用户名"  id="b1"/><br>

               <inputtype="password" value="" id="b2"/><br>

               <input type="button" value="登陆"  id="b3"/><br>

</body>

<scriptlanguage="JavaScript">

$(document).ready(

       function(){

              //绑定获得焦点focus()事件

              $('#b1').focus(

                     function(){

                            //先获取当前值

                            $curVal=$(this).val();

                            if($curVal==this.defaultValue){

                                   //应当设置为" "

                                   $(this).val("");

                            }else{

                                   $(this).val($curVal);

                            }

                     }

              );

              //再绑定一个失去焦点blur()事件

              $('#b1').blur(

                     function(){

                            //先获取当前值

                            $curVal=$(this).val();

                            if($curVal==""){

                                   //应当设置为" "

                                   $(this).val(this.defaultValue);

                            }else{

                                   $(this).val($curVal);

                            }

                     }

              );

       }

);

</script>

</html>

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!