<button> 是表單中功能最豐富、彈性最高的互動元素。與 <input type="button|submit|reset"> 不同,<button> 可包含**任意流式內容** (文字、圖片、圖示、甚至巢狀結構),並提供更精細的型別控制。
| 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 | 覆蓋表單 action | type="submit" 時生效 |
formmethod | 覆蓋表單 method | GET/POST |
formenctype | 覆蓋表單 enctype | multipart/form-data 等 |
formtarget | 覆蓋表單 target | _blank, _self... |
formnovalidate | 提交時跳過驗證 | type="submit" 時生效 |
popovertarget | 控制 Popover API 元素 (HTML 新增) | 現代瀏覽器支援中 |
popovertargetaction | toggle/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><input type="button|submit"> 可接受<button>**,語意更清晰、樣式控制更靈活、無障礙支援更完整。善用 <button> 的豐富內容模型與精確 type 控制,打造無障礙、可維護、視覺豐富的表單互動體驗。