| 特性 | readonly | disabled |
|---|---|---|
| 適用元素 | <input type="text/password/email/...>, <textarea> | 所有表單元素 (input, select, textarea, button, fieldset 等) |
| 使用者可編輯 | 否 | 否 |
| 可獲得焦點 | 是 (可 Tab 聚焦、複製文字) | 否 (不可 Tab、不可互動) |
| 表單提交時攜帶值 | 是 | 否 (瀏覽器不會送出) |
| 視覺預設樣式 | 正常 (可自訂) | 灰色禁用外觀 (瀏覽器預設) |
| CSS 偽類 | :read-only, :read-write | :disabled, :enabled |
<form id="demoForm" action="/submit" method="get">
<input name="q1" type="text" value="readonly" readonly>
<input name="q2" type="text" value="disabled" disabled>
<input type="submit" value="送出">
</form>
送出後 URL 為 /submit?q1=readonly,q2 完全不會出現在查詢字串中。
disabled=true 直到回應返回。fieldset disabled 批次禁用)。// === readonly ===
$('input').prop('readonly', true); // 設為唯讀
$('input').prop('readonly', false); // 移除唯讀
$('input').removeAttr('readonly'); // 同效,語意上移除屬性
// 判斷
if ($('input').prop('readonly')) { ... }
// === disabled ===
$('input').prop('disabled', true); // 禁用
$('input').prop('disabled', false); // 啟用
$('input').removeAttr('disabled'); // 同效
// 判斷
if ($('input').prop('disabled')) { ... }
重要:jQuery 1.6+ 請統一使用 .prop() 處理布林屬性 (disabled, readonly, checked, selected);.attr() 僅處理 HTML 屬性字串值。.removeAttr() 會移除屬性並觸發瀏覽器重繪,效能略低於 .prop('xxx', false)。
若需「不可編輯但仍提交」且外觀像 disabled:
<input id="myInput" type="text" value="不可編輯但會提交" readonly
style="background-color: #eee; cursor: not-allowed; color: #666;">
或加上 pointer-events: none; 完全阻擋滑鼠互動 (但仍可 Tab 聚焦)。
var input = document.getElementById('myInput');
// 啟用/禁用 disabled
input.disabled = true; // 禁用
input.disabled = false; // 啟用
// 唯讀
input.readOnly = true; // 注意大小寫:readOnly (駝峰)
input.readOnly = false;
// 移除屬性 (IE6/7 需用 removeAttribute)
input.removeAttribute('disabled');
input.removeAttribute('readonly');
readonly = 「看得到、複製得到、提交得到,改不了」;disabled = 「看得到、其他全不能,也不提交」。根據「是否需要隨表單提交」決定選用哪一個,並善用 .prop() 正確操作。