在js(jquery)中獲得文字框焦點和失去焦點的方法

來源:互聯網
上載者:User

先來看javascript的直接寫在了input上
複製代碼 代碼如下:
<input name="pwuser" type="text" id="pwuser" class="input" value="樓盤帳號" onBlur="if(this.value=='') this.value='樓盤帳號';" onFocus="if(this.value=='樓盤帳號') this.value='';" />
<input name="pwpwd" type="password" class="input1" value="******" onBlur="if(this.value=='') this.value='******';" onFocus="if(this.value=='******') this.value='';">

jquery實現方法

對於元素的焦時間點事件,我們可以使用jQuery的焦點函數focus(),blur()。

focus():得到焦點時使用,和javascript中的onfocus使用方法相同。
如:
複製代碼 代碼如下:
$("p").focus(); 或$("p").focus(fn)

blur():失去焦點時使用,和onblur一樣。
如:
複製代碼 代碼如下:
$("p").blur(); 或$("p").blur(fn)

執行個體
複製代碼 代碼如下:
<form>
<label for="searchKey" id="lbSearch">搜神馬?</label> 這裡label覆蓋在文字框上,可以更好的控制樣式
<input id="searchKey" type="text" />
<input type="submit" value="搜尋" />
</form>

jquery代碼
複製代碼 代碼如下:
$(function() {
$('#searchKey').focus(function() {
$('#lbSearch').text('');
});
$('#searchKey').blur(function() {
var str = $(this).val();
str = $.trim(str);
if(str == '')
$('#lbSearch').text('搜神馬?');
});
})

好了相當的不錯吧

聯繫我們

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