zoukankan      html  css  js  c++  java
  • jQuery之文本框得失焦点

    版本一

    css代码部分:

    .focus { 
         border: 1px solid #f00;
         background: #fcc;
    } 

    当焦点获得时,添加focus样式,添加边框,并改背景色为#fcc

    html代码部分:

    <body>
        <form action="" method="post" id="regForm">
            <fieldset>
                <legend>个人基本信息</legend>
                    <div>
                        <label  for="username">名称:</label>
                        <input id="username" type="text" />
                    </div>
                    <div>
                        <label for="pass">密码:</label>
                        <input id="pass" type="password" />
                    </div>
                    <div>
                        <label for="msg">详细信息:</label>
                        <textarea id="msg" rows="2" cols="20"></textarea>
                    </div>
            </fieldset>
        </form>
    </body>

    这里有两个input,一个textare框。

    :input匹配 所有 input, textarea, select 和 button 元素。

    jQuery代码部分:

    <script type="text/javascript">
        $(function(){
            $(":input").focus(function(){
                  $(this).addClass("focus");
            }).blur(function(){
                  $(this).removeClass("focus");
            });
        })
        </script>

    用:input匹配所有的input元素,当获取焦点时,就添加样式focus,通过$(this)自动识别当前的元素。focus()方法是获取焦点事件发生时执行的函数。blur()方法是失去焦点事件发生时执行的函数。

    版本二:

    有时候文本框里有默认的内容,作为提示信息,获取焦点后,要让它消失。可以做如下的改造:

    <script type="text/javascript">
        $(function(){
            $(":input").focus(function(){
                  $(this).addClass("focus");
                  if($(this).val() ==this.defaultValue){  
                      $(this).val("");           
                  } 
            }).blur(function(){
                 $(this).removeClass("focus");
                 if ($(this).val() == '') {
                    $(this).val(this.defaultValue);
                 }
            });
        })
        </script>

    做个逻辑判断,如果值为默认值,就将文本框中的内容清空。

    失去焦点,如果文本框中为空,也就是没有输入内容,就将值还设为默认值。

    这是一个简单的逻辑。

  • 相关阅读:
    APICloud学习笔记之图片缓存
    正则表达式笔记01
    hahah
    panel 绑定鼠标滚轮事件
    C#无边框窗体移动 将事件绑定到想实现的控件上
    消消看最高分破解
    字符串补齐
    ant android打包--学习第一弹
    Windsock套接字I/O模型学习 --- 第三章
    Lua 垃圾收集机制
  • 原文地址:https://www.cnblogs.com/jiqing9006/p/2685039.html
Copyright © 2011-2022 走看看