萬盛學電腦網

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

HTML <button> 元素核心屬性與行為差異:type、form、disabled、popover 等

核心屬性速查

屬性值/類型說明預設/備註
typesubmit | reset | button表單提交/重置/無預設行為submit (表單內) / button (表單外) — 務必顯式指定
disabledboolean禁用:不可聚焦、不提交、不觸發 click、樣式灰化false
formform id關聯表單 (可置於 form 外部)最近祖先 form
formactionURL覆蓋 form action (type=submit)--
formenctypemultipart/form-data | application/x-www-form-urlencoded | text/plain覆蓋 form enctype--
formmethodget | post | dialog覆蓋 form method--
formnovalidateboolean跳過驗證提交false
formtarget_blank | _self | _parent | _top | framename覆蓋 form target--
namestring提交時作為鍵值對 (name=value)--
valuestring提交值 (同 name 按鈕只提交被點擊者)--
autofocusboolean頁面載入自動聚焦 (每頁僅一個)false
popoverauto | manualHTML Popover API 觸發器 (實驗中)--
popovertargetelement id目標 popover 元素 id--
popovertargetactiontoggle | show | hide動作類型toggle
commandstringCommand API 指令識別 (實驗中)--
commandforelement id目標命令元素--

type 差異實測

<form action="/submit" method="post">
  <input name="q">
  <button type="submit">送出</button>      <!-- 觸發 form submit -->
  <button type="reset">重置</button>       <!-- 重置表單欄位 -->
  <button type="button" onclick="doSomething()">動作</button> <!-- 僅 JS -->
</form>

陷阱:在 <form> 內無 type 的 <button> 等同 type="submit",易造成非預期提交。

Form 屬性組合實戰:按鈕置於表單外部

<form id="search-form" action="/search" method="get">
  <input name="q" placeholder="關鍵字">
</form>

<button type="submit" form="search-form" formaction="/search-advanced" formmethod="post">
  進階搜尋
</button>

無障礙關鍵點

  • disabled 會自動從無障礙樹移除、不可聚焦;若需保持可聚焦但禁用,改用 aria-disabled="true" + CSS pointer-events:none; opacity:0.5;
  • 純圖示按鈕**必須**提供 aria-label 或內含 <span class="sr-only">文字</span>
  • type="button" 的按鈕在表單外不會觸發任何原生行為,適合 JS 綁定

HTML5.1/最新提案新增功能

  • Popover API:<button popovertarget="my-popover">開啟</button> + <div id="my-popover" popover>內容</div> — 無 JS 實現彈出層
  • Command API:<button commandfor="cmd-save"> 統一命令來源 (菜單/快捷鍵/工具列共用)
  • Invoker Commands:聲明式觸發 <button command="copy">
copyright © 萬盛學電腦網 all rights reserved