表單整體禁用/啟用是「提交中」「唯讀模式」「權限控制」的常見需求。本文對比逐個遍歷、fieldset.disabled、form.disabled(提議中)、CSS pointer-events 四種方案,並處理無障礙屬性、驗證狀態保持、動態新增控件同步。
| 方案 | 語法 | 優點 | 缺點 | 支援度 |
|---|---|---|---|---|
遍歷 querySelectorAll | form.querySelectorAll('input,select,textarea,button').forEach(e=>e.disabled=true) | 精確控制、可排除特定控件 | 動態新增需重新綁定、性能稍差 | 全瀏覽器 |
fieldset.disabled | fieldset.disabled = true | 原生語意、自動遞歸禁用所有後代、無需遍歷 | 無法排除例外、legend 內控件不受影響 | 全瀏覽器(IE9+) |
CSS pointer-events:none | form.style.pointerEvents='none'; form.style.opacity=0.6 | 極簡、視覺即禁用 | 鍵盤仍可聚焦、Tab 鍵可進入、表單提交仍發送數據 | IE11+ |
form.disabled (HTML 標準草案) | form.disabled = true | 一鍵禁用整個表單 | **瀏覽器尚未實現** | 無 |
<form id="myForm">
<fieldset id="fs-main">
<input name="username">
<select name="role"><option>Admin</option></select>
<textarea name="bio"></textarea>
</fieldset>
<!-- 始終啟用的提交按鈕放在 fieldset 外 -->
<button type="submit">提交</button>
</form>
<script>
function setFormDisabled(formId, disabled) {
const fs = document.querySelector(`#${formId} fieldset`);
if (fs) fs.disabled = disabled;
// 同步 aria-disabled 供螢幕閱讀器
fs?.querySelectorAll('input,select,textarea,button').forEach(el => {
el.setAttribute('aria-disabled', disabled);
});
}
// 使用
setFormDisabled('myForm', true); // 禁用
setFormDisabled('myForm', false); // 啟用
// 使用 MutationObserver 監聽 fieldset 內新增節點
const fs = document.getElementById('fs-main');
new MutationObserver(mutations => {
if (fs.disabled) {
mutations.forEach(m => m.addedNodes.forEach(node => {
if (node.matches?.('input,select,textarea,button')) {
node.disabled = true;
node.setAttribute('aria-disabled', 'true');
}
}));
}
}).observe(fs, { subtree: true, childList: true });
禁用狀態下,required、pattern 等驗證**不觸發**。恢復啟用後,若需即時驗證,可手動調用 el.reportValidity() 或 form.checkValidity()。
aria-disabled="true",啟用時移除或設為 false。tabIndex=-1 防止鍵盤聚焦到禁用控件(disabled 原生已阻止聚焦)。opacity:0.6; cursor:not-allowed),不依賴瀏覽器默認灰色。