SVGStyleElement: disabled 屬性

Baseline 已廣泛支援

此功能已成熟,可跨多種裝置和瀏覽器版本使用。自 2022 年 8 月起,所有瀏覽器均已支援此功能。

SVGStyleElement.disabled 屬性可用於獲取和設定樣式表是否被停用(true)或啟用(false)。

請注意,SVG <style> 元素上沒有對應的 disabled 屬性。

如果樣式表被停用,或者沒有關聯的樣式表,則返回 true;否則返回 false。預設值為 false(如果有關聯的樣式表)。

該屬性可用於啟用或停用關聯的樣式表。當沒有關聯的樣式表時,將屬性設定為 true 無效。

示例

停用 SVG 中定義的樣式

此示例演示瞭如何以程式設計方式設定在 HTML SVG 定義中定義的樣式的 disabled 屬性。

HTML

HTML 包含一個用於 <circle> 的 SVG 定義,其中包含一個 <style> 元素,以及一個將用於停用樣式的按鈕。

html
<button>Enable</button>
<svg
  xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink">
  <style id="circle_style_id">
    circle {
      fill: gold;
      stroke: green;
      stroke-width: 3px;
    }
  </style>
  <circle cx="50" cy="50" r="25" />
</svg>

JavaScript

下面的程式碼透過其 id 獲取 style 元素(一個 SVGStyleElement),然後將其設定為 disabled。由於樣式已在 SVG 中定義,因此它已經存在,所以此操作應該會成功。

js
const svg = document.querySelector("svg");
const style = svg.getElementById("circle_style_id");
style.disabled = true;

然後,我們為按鈕新增一個事件處理程式,該處理程式會切換 disabled 狀態和按鈕文字。

js
const button = document.querySelector("button");

button.addEventListener("click", () => {
  style.disabled = !style.disabled;
  button.textContent = style.disabled ? "Enable" : "Disable";
});

結果

結果如下所示。按下按鈕即可切換用於圓形的樣式的 disabled 屬性。

停用以程式設計方式定義的樣式

此示例與上一個非常相似,不同之處在於樣式是以程式設計方式定義的。

請注意,您可以同時應用 SVG 原始檔和以程式設計方式定義的多個樣式。此示例主要用於演示如何從外部建立樣式,並說明樣式可以何時被停用。

HTML

HTML 與前一個示例類似,但 SVG 定義不包含任何預設樣式。

html
<button>Enable</button>
<svg
  xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink">
  <circle cx="50" cy="50" r="25" />
</svg>

JavaScript

首先,我們建立新的 SVG 樣式節點。這可以透過以下步驟完成:首先使用 Document.createElementNS() 在 SVG 名稱空間中建立一個 style 元素,然後建立並附加一個包含樣式定義的文字節點,最後將該節點附加到上面定義的 SVG 中。

注意:您必須使用 Document.createElementNS() 而不是 Document.createElement() 來建立樣式,否則預設情況下您將建立一個等效的 HTML style 元素。

js
const svg = document.querySelector("svg");

// Create the `style` element in the SVG namespace
const style = document.createElementNS("http://www.w3.org/2000/svg", "style");
const node = document.createTextNode("circle { fill: red; }");
svg.appendChild(style);
style.appendChild(node);

然後,我們停用該樣式。請注意,這是將屬性設定為 true 能夠成功的最早時機。在此之前,SVG 沒有關聯的樣式,因此該值預設為 false

js
// Disable the style
style.disabled = true;

最後,我們為按鈕新增一個事件處理程式,該處理程式會切換 disabled 狀態和按鈕文字(這與前一個示例相同)。

js
const button = document.querySelector("button");

button.addEventListener("click", () => {
  style.disabled = !style.disabled;
  button.textContent = style.disabled ? "Enable" : "Disable";
});

結果

結果如下所示。按下按鈕即可切換用於圓形的樣式的 disabled 狀態。

規範

規範
Scalable Vector Graphics (SVG) 2
# __svg__SVGStyleElement__disabled

瀏覽器相容性

另見