HTML5 新增 input type(續)
| type | 適用場景 | 移動端鍵盤 | 驗證/值格式 |
datetime-local | 本地日期時間(無時區) | 日期時間選擇器 | YYYY-MM-DDThh:mm |
month | 年月 | 月份選擇器 | YYYY-MM |
week | 年周 | 周選擇器 | YYYY-Www |
time | 時間 | 時間選擇器 | hh:mm 或 hh:mm:ss |
color | 顏色選擇 | 原生拾色器 | #RRGGBB 小寫 |
search | 搜索框 | 帶清除鈕、圓角 | 文本,可配 incremental |
tel | 電話號碼 | 撥號盤 | 無格式強制,配合 pattern |
進階驗證屬性
| 屬性 | 類型 | 說明 | 示例 |
pattern | Regex | 自定義格式正則,需配合 title 提示 | pattern="[0-9]{6}" title="6位數字驗證碼" |
min/max | Number/Date | 最小/最大值(含邊界) | min="18" max="99" |
step | Number | 步長/精度 | step="0.01" (價格) |
minlength/maxlength | Integer | 字符長度限制 | minlength="8" maxlength="20" |
required | Boolean | 必填,提交時瀏覽器原生攔截 | required |
multiple | Boolean | email/file 允許多值 | <input type="file" multiple> |
accept | MIME/Ext | 文件類型過濾 | accept="image/*,.pdf" |
autocomplete | Token | 瀏覽器自動填充提示 | autocomplete="new-password" |
無障礙關鍵:Label 綁定與 ARIA
<!-- 顯式綁定(推薦) -->
<label for="user-name">姓名</label>
<input type="text" id="user-name" name="name" required>
<!-- 隱式包裹 -->
<label>郵箱 <input type="email" name="email"></label>
<!-- 無法用 label 時:aria-label / aria-labelledby -->
<input type="text" aria-label="搜索關鍵詞" placeholder="搜索...">
<span id="pwd-desc">至少8位,含大小寫數字</span>
<input type="password" aria-describedby="pwd-desc">
表單提交數據格式
application/x-www-form-urlencoded(默認):鍵值對編碼。
multipart/form-data:文件上傳必須。
text/plain:罕用。
- JS 獲取:
new FormData(form) → fetch(url, {method:'POST', body: formData})。
樣式鉤子偽類
input:valid { border-color: green; }
input:invalid { border-color: red; }
input:required { background: #fffde7; }
input:focus:invalid { outline: 2px solid red; }
input:user-invalid { /* Firefox: 用戶交互後才顯示無效 */ }