萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML <input> 標籤完整指南 (v2):22 種 type、表單屬性、驗證 API 與無障礙綁定

input 元素完整參考 v2:類型對照表、核心屬性、Constraint Validation API、無障礙實踐

type 類型完整對照 (HTML Living Standard)

typeUI 外觀資料型別驗證關鍵屬性
hidden不顯示string無value
text單行文字stringpattern, maxlengthlist, placeholder, autocomplete
search搜尋框 (含清除鈕)string同 text同 text
tel電話 (無內建驗證)stringpatternautocomplete="tel"
url網址URL stringURL 格式autocomplete="url"
email郵件email stringEmail 格式multiple, autocomplete="email"
password遮罩文字stringpattern, minlengthautocomplete="current-password/new-password"
date日期選擇器YYYY-MM-DDmin/max/stepreadonly 建議搭配
time時間選擇器HH:MM[:SS]min/max/step
datetime-local日期時間 (無時區)YYYY-MM-DDTHH:MMmin/max/step
month年月選擇YYYY-MMmin/max/step
week年週選擇YYYY-Wwwmin/max/step
number數字步進器numbermin/max/stepinputmode="numeric"
range滑桿numbermin/max/steporient="vertical" (非標準)
color顏色選擇器#rrggbb無list 可預設調色盤
checkbox複選框booleanrequiredvalue (提交值), indeterminate (JS)
radio單選鈕stringrequired (群組)name 相同者互斥
file檔案選擇FileListaccept, multiplecapture="user/environment" (行動裝置相機)
submit提交按鈕--value=按鈕文字, formaction/formmethod 覆蓋 form
image圖片提交--src, alt, width, height
reset重置按鈕--value=按鈕文字
button無預設行為按鈕--配合 JS 事件

共用核心屬性

  • name:提交鍵名 (必填,除 submit/image/button 外)。
  • value:初始/提交值。
  • disabled:禁用 (不提交、不可聚焦、灰色)。
  • readonly:唯讀 (可聚焦、可複製、會提交)。
  • required:必填驗證。
  • autofocus:自動聚焦 (每頁限一)。
  • autocomplete:瀏覽器自動填入策略。
  • form:關聯非祖先 form (id)。
  • list:關聯 <datalist> (id)。
  • placeholder:提示文字 (非 label 替代品)。
  • aria-label/aria-labelledby:無障礙名稱 (無視覺 label 時)。

Constraint Validation API (JS 控制驗證)

const input = document.querySelector('input[required]');
input.checkValidity();        // true/false
input.reportValidity();       // 顯示瀏覽器原生錯誤泡泡
input.setCustomValidity('自訂錯誤訊息'); // 設定自訂錯誤
input.validity;               // ValidityState 物件 {valueMissing, typeMismatch, patternMismatch, tooLong, tooShort, rangeUnderflow, rangeOverflow, stepMismatch, badInput, customError}

無障礙綁定:label 三種方式

  1. 明確關聯 (推薦):<label for="id">標籤</label> <input id="id">
  2. 隱含關聯:<label>標籤 <input></label>
  3. ARIA 標籤:<input aria-label="標籤"> 或 aria-labelledby="id" (無視覺 label 時)。

正確使用 <label> 能讓螢幕閱讀器朗讀、點擊放大點擊區域、瀏覽器自動填入正確識別欄位。

copyright © 萬盛學電腦網 all rights reserved