input 輸入框獲得/失去焦點時隱藏/顯示文字(jquery版)

來源:互聯網
上載者:User

input 輸入框獲得和失去焦點時隱藏或者顯示文字我們先看下
輸入框預設狀態:

輸入框擷取焦點狀態:

大家可以看的搜尋輸入框,預設顯示著“使用者名稱/Email”的提示,當這個 input 輸入框獲得焦點時,就自動清空等待使用者輸入,當使用者啥也沒輸入就離開這個 input 輸入框時,輸入框內又再次顯示“使用者名稱/Email”的提示。是不是很常見?很多搜尋、登入、表單都會用到這個效果,但是我看了N多個網站,有90%以上是這麼實現的: 複製代碼 代碼如下:<input type="text" value="搜尋索引鍵" onfocus="if(this.value == '搜尋索引鍵') this.value = ''" onblur="if(this.value =='') this.value = '搜尋索引鍵'" />

我是非常反對把 javascript 寫在 html 標籤裡的,這和 style 寫在 html 標籤裡一樣,雖然不違反 W3C 標準,但也不推薦這麼寫。因為:
1.完全沒有複用性可言,如果是個表單,輸入框很多,每個都需要這樣的效果,那就每個都這麼處理嗎?
2.如果要修改其中的提示文字,費時費力又不好維護。
3.我們倡導結構(html)、表現(css)、行為(javascript)三者分離,這才是一個好的頁面。
那要怎麼寫才能實現這個效果,而且既有複用性,又好維護,又不需要把 js 寫進 html 裡呢?
具體方法如下:
首先肯定是引入jQuery
Html代碼: 複製代碼 代碼如下:<div><input type="text" value="提示測試" class="input_test" /></div>
<div><input type="text" value="請輸入搜尋關鍵" class="input_test" /></div>

jQuery代碼: 複製代碼 代碼如下:<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('.input_test').bind({
focus:function(){
if (this.value == this.defaultValue){
this.value="";
}
},
blur:function(){
if (this.value == ""){
this.value = this.defaultValue;
}
}
});
})
</script>

只要在實現的input輸入框加上”input_test”這個class就可以輕鬆實現了
查看:Demo

聯繫我們

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