HTML 屬性分為全域屬性 (所有元素通用)、元素專屬屬性、事件處理屬性、ARIA 無障礙屬性、表單驗證屬性。理解分類有助於精準套用與除錯。
| 屬性 | 用途 | 範例 |
|---|---|---|
class | CSS/JS 掛鉤 | class="btn btn-primary" |
id | 唯一識別碼 | id="main-nav" |
style | 內嵌樣式 (不建議) | color: red; |
title | 提示文字 | title="點擊查看詳情" |
lang | 元素語言 | lang="en" |
dir | 文字方向 | dir="rtl" |
hidden | 隱藏元素 | hidden 或 hidden="until-found" |
data-* | 自訂資料屬性 | data-user-id="123" |
tabindex | 鍵盤焦點順序 | tabindex="0" (納入順序), -1 (移除) |
contenteditable | 可編輯內容 | contenteditable="plaintext-only" |
spellcheck | 拼字檢查 | spellcheck="true" |
draggable | 拖放 API | draggable="true" |
slot | Web Components 插槽 | slot="header" |
is | 自訂元素擴充 | <button is="my-button"> |
part | Shadow DOM 樣式暴露 | part="icon" |
exportparts | Shadow DOM 部分轉發 | exportparts="icon:btn-icon" |
onclick, ondblclick, onmousedown/up/move/over/out/enter/leave, onwheel, oncontextmenuonkeydown/up/pressonsubmit, onreset, onchange, oninput, onfocus/blur, oninvalidoncopy/cut/pasteonplay/pause/ended/timeupdate/volumechangeonload/error/resize/scroll (僅 body/window)ondrag/start/end/enter/leave/over/droponpointerdown/up/move/over/out/enter/leave/cancel/got/lost最佳實踐:HTML 避免內聯事件,改用 element.addEventListener('click', handler) 關注點分離、支援多監聽器、便於移除。
| 分類 | 屬性範例 |
|---|---|
| 角色 | role="button|dialog|menu|tablist|alert|status|region|search|navigation" |
| 狀態/屬性 | aria-expanded, aria-hidden, aria-disabled, aria-selected, aria-checked, aria-pressed, aria-current, aria-live="polite|assertive", aria-atomic, aria-busy |
| 關聯 | aria-labelledby, aria-describedby, aria-controls, aria-owns, aria-activedescendant |
| 輸入 | aria-required, aria-invalid, aria-placeholder, aria-autocomplete |
原則:優先使用原生語意標籤 (<button>, <nav>, <main>),原生已內建 ARIA 語意。
| 屬性 | 適用 | 說明 |
|---|---|---|
required | input, select, textarea | 必填,瀏覽器原生驗證 |
pattern | input (text, tel, email, url, password) | RegExp 模式驗證,需配合 title 提示 |
min/max/step | input (number, date, range, time) | 數值/日期範圍與步進 |
minlength/maxlength | input, textarea | 字元長度限制 |
multiple | input (file, email), select | 允許多值 |
accept | input[type=file] | 限制檔案類型 (MIME/副檔名) |
autocomplete | input, form | 瀏覽器自動填入提示 (on/off/email/username/new-password...) |
novalidate | form | 停用瀏覽器原生驗證 (自行實作) |
form | input, select, textarea, button, output, label, fieldset | 關聯非巢狀 form ID |
formaction/formenctype/formmethod/formtarget/formnovalidate | button, input[type=submit/image] | 覆寫 form 屬性 |
<a>:href, target, rel, download, hreflang, type, referrerpolicy<img>:src, alt, srcset, sizes, loading, decoding, fetchpriority, width, height, crossorigin, referrerpolicy<input>:type, name, value, placeholder, disabled, readonly, autofocus, list (關聯 datalist)<meta>:charset, name, content, http-equiv, property (Open Graph)<link>:rel, href, as, crossorigin, media, sizes, type, fetchpriority<script>:src, type (module/importmap), async, defer, nomodule, crossorigin, integrity (SRI), referrerpolicy, fetchpriority