萬盛學電腦網

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

HTML <button> 標籤完整指南:type 屬性、內容模型與表單提交行為

HTML <button> 標籤:表單互動核心元素完整解析

<button> 是表單中功能最豐富、彈性最高的互動元素。與 <input type="button|submit|reset"> 不同,<button> 可包含**任意流式內容** (文字、圖片、圖示、甚至巢狀結構),並提供更精細的型別控制。

關鍵屬性:type (決定表單行為)

type 值行為預設值適用場景
submit提交表單資料到 action URL**預設值** (若省略 type)送出按鈕、登入、註冊、搜尋
reset重置表單所有欄位為初始值—清除表單、取消編輯
button無預設行為,需 JS 綁定事件—自訂功能:開啟 Modal、觸發 AJAX、計算...

⚠️ 關鍵陷阱:IE 預設 type="button",其他瀏覽器與標準預設 type="submit"。**永遠明確指定 type 屬性**,避免跨瀏覽器行為不一致導致表單誤送出。

內容模型優勢:豐富的按鈕內容

<!-- 圖示 + 文字 -->
<button type="submit">
  <svg class="icon"><use xlink:href="#search-icon"></use></svg>
  搜尋
</button>

<!-- 多行文字與強調 -->
<button type="button" class="btn-primary">
  <strong>立即開始</strong><br>
  <small>免費試用 30 天,無需信用卡</small>
</button>

<!-- 純圖示按鈕 (需 aria-label) -->
<button type="button" aria-label="關閉視窗">
  <svg><use xlink:href="#close-icon"></use></svg>
</button>

<input> 僅能透過 value 顯示純文字,無法放入 HTML 內容。

其他重要屬性

屬性功能備註
name表單提交時的鍵名同名多按鈕可區分哪個被點擊
value提交時的值配合 name 使用,如 name="action" value="save"
disabled停用按鈕 (不可聚焦、不提交、灰色)布林屬性
autofocus頁面載入自動聚焦每頁僅一個元素可用
form關聯表單 ID (HTML5)按鈕可放在 <form> 外部
formaction覆蓋表單 actiontype="submit" 時生效
formmethod覆蓋表單 methodGET/POST
formenctype覆蓋表單 enctypemultipart/form-data 等
formtarget覆蓋表單 target_blank, _self...
formnovalidate提交時跳過驗證type="submit" 時生效
popovertarget控制 Popover API 元素 (HTML 新增)現代瀏覽器支援中
popovertargetactiontoggle/show/hide配合 popovertarget

完整表單範例:多按鈕區分動作

<form action="/api/article" method="post">
  <textarea name="content" required></textarea>
  <div class="actions">
    <button type="submit" name="action" value="draft">儲存草稿</button>
    <button type="submit" name="action" value="publish" class="btn-primary">發布文章</button>
    <button type="button" id="previewBtn">預覽</button>
    <button type="reset">重置</button>
  </div>
</form>

<script>
  // 後端可透過 $_POST['action'] 判斷是 'draft' 或 'publish'
  document.getElementById('previewBtn').addEventListener('click', () => {
    // AJAX 取得預覽 HTML,開啟 Modal 顯示
  });
</script>

樣式重置與自訂 (跨瀏覽器一致)

button {
  /* 重置瀏覽器預設樣式 */
  appearance: none;
  border: none;
  background: none;
  padding: 0;
  margin: 0;
  font: inherit;
  color: inherit;
  cursor: pointer;
  /* 自訂樣式 */
  padding: 0.625rem 1.25rem;
  border-radius: 0.375rem;
  font-weight: 500;
  transition: background-color 0.2s, box-shadow 0.2s;
}
button:disabled { opacity: 0.6; cursor: not-allowed; }
button:focus-visible { outline: 2px solid #0d6efd; outline-offset: 2px; }

button vs input type="button|submit" 選擇指南

  • 需要**豐富內容** (圖示、多行、巢狀元素) → <button>
  • 簡單純文字按鈕、相容極舊環境 → <input type="button|submit"> 可接受
  • 現代開發**強烈建議統一使用 <button>**,語意更清晰、樣式控制更靈活、無障礙支援更完整。

善用 <button> 的豐富內容模型與精確 type 控制,打造無障礙、可維護、視覺豐富的表單互動體驗。

copyright © 萬盛學電腦網 all rights reserved