原需求:勾選複選框時將輸入框設為「不可見」。
修正需求:勾選時設為「唯讀狀態」,使用者可看見內容但無法編輯。
readonly="true":屬性值應為 readonly(布林屬性),非字串background:expression(this.readOnly=true):IE 專有 CSS Expression,已棄用且有安全風險readonly/disabled 狀態<input type="checkbox" id="chkControl" onchange="toggleReadonly(this)"> 鎖定輸入框
<input type="text" id="txtTarget" value="預設內容">
<script>
function toggleReadonly(checkbox) {
const input = document.getElementById('txtTarget');
input.readOnly = checkbox.checked; // 布林值直接指派
// 視覺回饋:唯讀時改變背景色
input.style.backgroundColor = checkbox.checked ? '#f5f5f5' : '';
}
</script>
function toggleDisabled(checkbox) {
const input = document.getElementById('txtTarget');
input.disabled = checkbox.checked;
}
差異比較:
| 特性 | readOnly | disabled |
|---|---|---|
| 使用者可見內容 | 是 | 是 |
| 可複製文字 | 是 | 是 |
| 可獲得焦點 | 是 | 否 |
| 表單提交時送出 | 是 | 否 |
| 預設樣式 | 正常 | 灰色禁用 |
$('#chkControl').on('change', function() {
$('#txtTarget').prop('readOnly', this.checked);
// 或 .prop('disabled', this.checked);
});
<input type="checkbox" id="chkAll" data-targets="field1 field2 field3">
<script>
document.getElementById('chkAll').addEventListener('change', function() {
const targetIds = this.dataset.targets.split(' ');
const isReadonly = this.checked;
targetIds.forEach(id => {
const el = document.getElementById(id);
if (el) {
el.readOnly = isReadonly;
el.style.backgroundColor = isReadonly ? '#e9ecef' : '';
}
});
});
</script>
input[readonly] {
background-color: #f8f9fa;
border-color: #ced4da;
cursor: not-allowed;
}
input:read-only { /* 現代瀏覽器支援 */
/* 唯讀專用樣式 */
}
控制表單元素狀態必須使用 JavaScript 設定 DOM 屬性(readOnly 或 disabled),CSS 僅能提供視覺回饋。根據業務需求選擇:需提交資料用 readOnly,完全禁用互動用 disabled。