HTMLStyleElement: disabled 屬性
HTMLStyleElement.disabled 屬性可用於獲取和設定樣式表是否被停用(true)或未被停用(false)。
請注意,HTML <style> 元素沒有相應的 disabled 屬性。
值
如果樣式表被停用,或者沒有關聯的樣式表,則返回 true;否則返回 false。預設值為 false(如果有關聯的樣式表)。
該屬性可用於啟用或停用關聯的樣式表。當沒有關聯的樣式表時,將該屬性設定為 true 無效。
示例
停用內聯樣式
本示例演示瞭如何以程式設計方式設定在 HTML 中使用 HTML <style> 元素定義的樣式的 disabled 屬性。請注意,您還可以使用 Document.styleSheets 訪問文件中的任何/所有樣式表。
HTML
HTML 包含一個 HTML <style> 元素,該元素將段落元素設定為藍色,一個段落元素,以及一個用於啟用和停用樣式的按鈕。
<button>Enable</button>
<style id="InlineStyle">
p {
color: blue;
}
</style>
<p>Text is black when style is disabled; blue when enabled.</p>
<p></p>
JavaScript
下面的程式碼透過 id 獲取 style 元素,然後將其設定為停用。由於樣式已存在(因為它定義在 SVG 中),所以這應該會成功。
const style = document.getElementById("InlineStyle");
style.disabled = true;
然後,我們為按鈕新增一個事件處理程式,該處理程式將切換 disabled 值和按鈕文字。
const button = document.querySelector("button");
button.addEventListener("click", () => {
style.disabled = !style.disabled;
const buttonText = style.disabled ? "Enable" : "Disable";
button.innerText = buttonText;
});
結果
結果如下所示。按下按鈕可切換用於段落文字的樣式的 disabled 屬性值。
停用以程式設計方式定義的樣式
此示例與上面的示例非常相似,但樣式是以程式設計方式定義的。
HTML
HTML 與前一個案例類似,但定義不包含任何預設樣式。
<button>Enable</button>
<p>Text is black when style is disabled; blue when enabled.</p>
<p></p>
JavaScript
首先,我們在 HTML 上建立新的 style 元素。這透過首先使用 Document.createElement() 建立一個 style 元素,建立並附加一個帶有樣式定義的文字節點,然後將 style 元素附加到文件主體來完成。
// Create the `style` element
const style = document.createElement("style");
const node = document.createTextNode("p { color: blue; }");
style.appendChild(node);
document.body.appendChild(style);
然後,我們可以如下所示停用樣式。請注意,這是將屬性設定為 true 會成功的最早時間點。在此之前,文件沒有關聯的樣式,因此該值預設為 false。
// Disable the style
style.disabled = true;
最後,我們為按鈕新增一個事件處理程式,用於切換停用狀態和按鈕文字(這與前一個示例相同)。
const button = document.querySelector("button");
button.addEventListener("click", () => {
style.disabled = !style.disabled;
const buttonText = style.disabled ? "Enable" : "Disable";
button.innerText = buttonText;
});
結果
結果如下所示。按下按鈕可切換用於文字的樣式的 disabled 狀態。
規範
| 規範 |
|---|
| HTML # dom-style-disabled |
瀏覽器相容性
載入中…