在正式認識新成員之前,先來複習一下我們早已熟悉的那些傳統表單元素。它們构成了網頁表單的基礎:
<input type="text"> 文本輸入框
<input type="radio"> 單選按鈕
<input type="checkbox"> 複選框
<select><option> 下拉清單
<input type="password"> 密碼欄位
<input type="submit"> 提交按鈕
<input type="button"> 可點擊按鈕
<input type="image"> 圖片按鈕
<input type="hidden"> 隱藏欄位
<input type="reset"> 重置按鈕
<input type="file"> 檔案上傳欄位
到了 HTML5 時代,表單迎來了一次可觀的升級。它一口氣引入了多個全新的 input 類型,讓我們不必再依賴繁瑣的 JavaScript 腳本,就能實現更貼心的輸入提示與更自動化的資料驗證。以下逐一介紹這八個新成員。
email 類型專為填寫電子郵件地址而設計。當使用者提交表單時,瀏覽器會自動檢查內容是否符合郵件位址的格式,格式不正確便無法送出,省下了額外撰寫校驗規則的功夫。
<input type="email" name="user_email" />
url 類型提供了一個專門用來輸入網址的文本框,同樣會在提交時對位址格式進行驗證。
<input type="url" name="user_url" />
number 類型只用來填寫數值,還能透過 min、max、step 等屬性精確控制取值範圍與步進幅度。
<input type="number" name="number1" min="1" max="20" step="4" />
range 類型允許使用者在指定區間內挑選一個數字,在頁面上它呈現為一條可拖動的滑桿,操作直觀又方便。
<input type="range" name="range1" min="1" max="30" />
HTML5 一次補齊了各種類型的日期與時間選擇器,讓瀏覽器直接調出原生選擇介面:
date <input type="date">:選擇日、月、年
month <input type="month">:選擇月、年
week <input type="week">:選擇週與年
time <input type="time">:選擇時間(時、分)
datetime <input type="datetime">:選擇日期與時間(UTC 時間)
datetime-local <input type="datetime-local">:選擇日期與時間(本地時間)
search 類型專為輸入搜尋關鍵字而生,語義明確,便於瀏覽器與輔助工具理解其用途。
<input type="search" name="search1" />
input[type="search"]{
-webkit-appearance:textfield;
}
tel 類型用於填寫電話號碼,方便行動裝置調出數字鍵盤,提升輸入效率。
<input type="tel" name="tel" />
color 類型提供了一個調色盤介面,讓使用者能直觀地挑選並設定顏色。
<input type="color" name="color" />
這些新增的輸入類型,讓表單在語義化與使用者體驗上都邁出了一大步。值得一提的是,對於不支援這些新類型的舊版瀏覽器,它們會自動退回普通文本框顯示,因此具備良好的向下相容性。