javascript和jquery實現設定和移除文字框預設值效果代碼_javascript技巧

來源:互聯網
上載者:User

這裡想實現的效果是:設定和移除文字框預設值,如下圖滑鼠放到文字框中的時候,灰字消失。

1.可以用簡單的方式,就是給input文字框加上onfocus屬性,如下代碼:

複製代碼 代碼如下:

<input id="keyword" name="keyword" size="10" class="inputstyle keywords" value="請輸入關鍵字進行搜尋"
   onfocus='if(this.value=="請輸入關鍵字進行搜尋"){this.value="";}; '
   onblur='if(this.value==""){this.value="請輸入關鍵字進行搜尋";};'>

其實onfocus屬性挺好用的,還可以在通過onfocus屬性改變css樣式,如下代碼:

複製代碼 代碼如下:

<input id="keyword" name="keyword" size="10" class="inputstyle keywords" value="請輸入關鍵字進行搜尋"
 onfocus='if(this.value=="請輸入關鍵字進行搜尋"){this.value="";}; this.className="input01"'
 onblur='if(this.value==""){this.value="請輸入關鍵字進行搜尋";}; this.className="input02"'>

2.也可以使用jquery實現:

複製代碼 代碼如下:

$(document).ready(function() {
        var vdefault = $('#keyword').val();

 $('#keyword').focus(function() {
            //獲得焦點時,如果值為預設值,則設定為空白
            if ($(this).val() == vdefault) {
                $(this).val("");
            }
        });
 $('#keyword').blur(function() {
            //失去焦點時,如果值為空白,則設定為預設值
            if ($(this).val()== "") {
                $(this).val(vdefault); ;
            }
        });
});

當然實現的方式還有很多種,這裡只是我使用過的...

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.