從使用者體驗出發,簡化操作步骤就是提升易用度。輸入框是最常被操作的元件,值得花點心思。以下四種效果聽起來複雜,實際上都只需一小段程式碼。
<form id="form1" name="form1" method="post" action="">
<label for="textfield">輸入內容:</label>
<input name="textfield" type="text" id="textfield"
value="Dreamweaver" onfocus="this.select()">
</form>
關鍵是 onfocus="this.select()"。使用者點進來時內容已全選,直接打字就能覆蓋,不必先 Ctrl+A。改用 onclick 效果相同,但 onfocus 更貼切——用 Tab 鍵移進來時也會觸發。
CSS 方案(推薦):
input:hover { border: 1px solid #F00; }
input:focus { border-color: #FF6600; background: #fffdf5; }
簡潔且效能好。要注意 :hover 在 IE6 上只對 a 元素有效,這是當年需要用 JS 的原因;現代瀏覽器完全支援,沒有這個顧慮。
JS 方案:
<input name="textfield" type="text" id="textfield" value="Dreamweaver"
onmouseover="this.style.borderColor='#FF6600'"
onmouseout="this.style.borderColor=''"
onfocus="this.select()">
只有在需要依條件動態決定顏色時才需要走這條路。
<input name="textfield" type="text" id="textfield" value="Dreamweaver"
onmouseover="this.style.borderColor='#FF6600'"
onmouseout="this.style.borderColor=''"
onfocus="if (value == 'Dreamweaver') { value = '' }"
onblur="if (value == '') { value = 'Dreamweaver' }">
邏輯是:聚焦時若內容還等於預設文字就清空;失焦時若內容是空的就把預設文字填回去。使用者有輸入新內容時不會被覆蓋。
這個做法有幾個缺點值得留意:預設文字會被當成真正的值送出(後端要另外判斷);用螢幕閱讀器時那段提示文字可能被朗讀成「內容」;而且如果表單送出後有驗證錯誤回填,判斷邏輯容易出錯。
<input type="search" name="user_search" placeholder="搜尋 W3School">
placeholder 天生解決了上述所有問題:提示文字不會成為值、聚焦時自動消失、不影響表單驗證、原生支援所有現代瀏覽器。
想要更進一步的視覺效果,可以自訂 placeholder 樣式:
::placeholder { color: #999; opacity: 1; } /* Firefox 需要 opacity:1 */
::-webkit-input-placeholder { color: #999; }
除了視覺效果,還有兩件事對易用度的影響更大。
第一,正確的 type 與 autocomplete。手機鍵盤會依 type 自動切換配置:
<input type="email" autocomplete="email">
<input type="tel" autocomplete="tel">
<input type="url" autocomplete="url">
<input type="number" inputmode="numeric">
用 email 會出現 @ 鍵,用 tel 會出現數字鍵盤,autocomplete 則能讓瀏覽器自動帶入已存資料。這對手機使用者的幫助遠大於邊框變色。
第二,一定要有 <label>。placeholder 不能取代 label——使用者一打字提示就消失了,之後回頭看會不知道這個欄位要填什麼。用 <label for> 關聯,視覺上可以放在欄位上方,螢幕閱讀器也能正確朗讀欄位名稱。
這些技巧的核心精神是:能用原生屬性解決的,就不要用 JS 硬湊。placeholder、type、autocomplete、label 這四樣,已經涵蓋了九成的輸入框優化需求。