DIV CSS 佈局教程網

取得與失去輸入框焦點:原生寫法與 jQuery focus/blur
編輯:關於JavaScript     

「滑到輸入框就消失提示文字、離開又補回來」是搜尋框最經典的互動細節。實作上就是兩個事件:onfocus 與 onblur。

最直接:寫在標籤上

<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='';">

這種寫法簡單直白,缺點是提示字樣混在 value 裡,使用者若真的想輸入「樓盤賬號」這四個字就會被清掉;密碼框把星號當提示也有同樣問題。當年因為沒有 placeholder,只能用這招。

jQuery 版本

jQuery 把焦點事件包成兩個方法,用法與原生事件一一對應:

focus():取得焦點時觸發,等同 onfocus。
$("p").focus();  或  $("p").focus(fn)

blur():失去焦點時觸發,等同 onblur。
$("p").blur();   或  $("p").blur(fn)

用 label 疊在輸入框上

比較漂亮的解法是讓 <label> 蓋住輸入框當提示文字,焦點事件裡只負責切換顯示,不污染 value:

<form>
  <label for="searchKey" id="lbSearch">搜神馬?</label>
  <!-- label 覆蓋在文本框上,可以更好的控制樣式 -->
  <input id="searchKey" type="text" />
  <input type="submit" value="搜索" />
</form>
$(function() {
  $('#searchKey').focus(function() {
    $('#lbSearch').text('');
  });

  $('#searchKey').blur(function() {
    var str = $(this).val();
    str = $.trim(str);
    if(str == '')
      $('#lbSearch').text('搜神馬?');
  });
})

這裡的 $.trim 是關鍵:使用者只打了幾個空白就離開時,提示仍該回來,否則畫面會一片空白。

今天寫這類互動,直接用 HTML5 的 placeholder 屬性就好,瀏覽器原生處理了顯示、清除與無障礙朗讀,一行都不用寫 JS:

<input id="searchKey" type="text" placeholder="搜神馬?" />

只有在需要更複雜行為(例如 focus 時加上 class 換邊框顏色、blur 時做即時驗證)時,才需要接手 focus/blur 事件。若使用 jQuery 3 之後,也建議改用 .on('focus blur', fn) 綁定,比 .focus() 這種簡寫更能統一管理事件。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved