萬盛學電腦網

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

HTML <input> 標籤完整指南:類型屬性大全、表單驗證、無障礙與最佳實踐

<input> 核心屬性

屬性說明
type控件類型(決定 UI 與驗證邏輯)
name表單提交鍵名(必填,否則不提交)
value初始/當前值
placeholder佔位提示(非替代 label)
required必填驗證
disabled禁用(不提交、不可聚焦、灰顯)
readonly只讀(可提交、可聚焦、可複製)
autocomplete自動完成提示(on/off/email/username/new-password…)
autofocus頁面加載自動聚焦(每頁僅一個)
form關聯表單 ID(可置於 form 外)
list關聯 <datalist> ID
pattern正則驗證(需配合 title 提示)
min/max/step數字/日期範圍與步長
accept文件類型過濾(image/*, .pdf, .docx)
capture媒體捕獲來源(user/environment)

type 類型大全(HTML5 新增標 ★)

type用途UI/驗證特性
text單行文本無特殊驗證
password密碼彈幕顯示、防自動填充
email ★郵箱內建格式驗證、移動鍵盤優化
url ★網址內建格式驗證
tel ★電話移動端彈出撥號盤
number ★數字上下箭頭、min/max/step 驗證
range ★滑塊視覺滑桿、配合 output 顯示值
date ★日期日期選擇器、ISO 8601 格式
datetime-local ★本地日期時間無時區
month/week ★月/周特定選擇器
time ★時間時間選擇器
color ★顏色拾色器、返回 #RRGGBB
checkbox多選布爾值、可配合 indeterminate
radio單選同 name 分組互斥
file上傳accept、multiple、capture
submit提交按鈕觸發 form submit
button普通按鈕無默認行為、配合 JS
reset重置按鈕恢復表單初始值
image圖片提交src、alt、提交座標 x/y
hidden隱藏字段不顯示、提交數據

無障礙關鍵:<label> 綁定

<!-- 方式一:for + id(推薦,點擊 label 聚焦 input) -->
<label for="username">用戶名</label>
<input type="text" id="username" name="username" required>

<!-- 方式二:包裹(無需 id) -->
<label>郵箱 <input type="email" name="email"></label>

表單驗證最佳實踐

  • 優先使用原生屬性(required, pattern, min/max, type)實現無 JS 驗證。
  • 自定義提示:input.setCustomValidity('錯誤信息') + reportValidity()。
  • 樣式鉤子::valid, :invalid, :required, :optional, :user-invalid (Firefox)。
  • 提交前統一檢查:form.checkValidity() / form.reportValidity()。

經典示例:登錄表單

<form action="/login" method="post" novalidate>
  <div>
    <label for="email">郵箱</label>
    <input type="email" id="email" name="email" required autocomplete="email" placeholder="you@example.com">
  </div>
  <div>
    <label for="pwd">密碼</label>
    <input type="password" id="pwd" name="password" required autocomplete="current-password" minlength="8">
  </div>
  <button type="submit">登錄</button>
</form>
copyright © 萬盛學電腦網 all rights reserved