jQuery 文字框得失焦點的執行個體介紹

來源:互聯網
上載者:User

jQuery 文字框得失焦點的執行個體介紹

 本篇文章主要是對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>

 

做個邏輯判斷,如果值為預設值,就將文字框中的內容清空。

 

失去焦點,如果文字框中為空白,也就是沒有輸入內容,就將值還設為預設值。

 

這是一個簡單的邏輯。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.