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

浏览器兼容性

另见