:disabled
:disabled CSS 偽類表示任何被停用的元素。如果一個元素無法被啟用(選中、點選、輸入等)或無法獲取焦點,則該元素處於停用狀態。該元素還具有啟用狀態,在該狀態下可以被啟用或獲取焦點。
試一試
label {
display: block;
margin-top: 1em;
}
*:disabled {
background-color: dimgrey;
color: linen;
opacity: 1;
}
<form>
<label for="name">Name:</label>
<input id="name" name="name" type="text" />
<label for="emp">Employed:</label>
<select id="emp" name="emp" disabled>
<option>No</option>
<option>Yes</option>
</select>
<label for="empDate">Employment Date:</label>
<input id="empDate" name="empDate" type="date" disabled />
<label for="resume">Resume:</label>
<input id="resume" name="resume" type="file" />
</form>
語法
css
:disabled {
/* ... */
}
示例
此示例展示了一個基本的配送表單。它使用 JavaScript 的 change 事件,允許使用者啟用/停用賬單欄位。
HTML
html
<form action="#">
<fieldset id="shipping">
<legend>Shipping address</legend>
<input type="text" placeholder="Name" />
<input type="text" placeholder="Address" />
<input type="text" placeholder="Zip Code" />
</fieldset>
<br />
<fieldset id="billing">
<legend>Billing address</legend>
<label for="billing-checkbox">Same as shipping address:</label>
<input type="checkbox" id="billing-checkbox" checked />
<br />
<input type="text" placeholder="Name" disabled />
<input type="text" placeholder="Address" disabled />
<input type="text" placeholder="Zip Code" disabled />
</fieldset>
</form>
CSS
css
input[type="text"]:disabled {
background: #cccccc;
}
JavaScript
點選複選框時切換停用的輸入欄位
js
const checkbox = document.querySelector("#billing-checkbox");
const billingItems = document.querySelectorAll('#billing input[type="text"]');
checkbox.addEventListener("change", () => {
billingItems.forEach((item) => {
item.disabled = !item.disabled;
});
});
結果
勾選/取消勾選複選框可更改賬單欄位的樣式。
規範
| 規範 |
|---|
| HTML # selector-disabled |
| 選擇器 Level 4 # disabled-pseudo |
瀏覽器相容性
載入中…