文档:styleSheets 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

styleSheetsDocument 接口的一个只读属性,它返回一个 StyleSheetList 集合,其中包含 CSSStyleSheet 对象。这些样式表是显式链接到或嵌入在文档中的。

返回的列表按以下顺序排序:

  • Link 标头检索到的样式表首先放置,并按标头顺序排序。
  • 从 DOM 检索到的样式表放在后面,并按树顺序排序。

示例

通过标题检索特定样式表

js
function getStyleSheet(uniqueTitle) {
  for (const sheet of document.styleSheets) {
    if (sheet.title === uniqueTitle) {
      return sheet;
    }
  }
}

访问样式表中的规则

您可以使用样式表、样式和 CSSRule 对象单独访问这些样式表及其规则,如下例所示,该示例会将所有样式规则选择器打印到控制台。

js
for (const styleSheet of document.styleSheets) {
  for (const rule of styleSheet.cssRules) {
    console.log(`${rule.selectorText}\n`);
  }
}

对于具有单个样式表的文档,其中定义了以下三个规则:

css
body {
  background-color: darkblue;
}
p {
  font-family: "Arial";
  font-size: 10pt;
  margin-left: 0.125in;
}
#lumpy {
  display: none;
}

此脚本输出以下内容:

BODY
P
#LUMPY

规范

规范
CSS 对象模型 (CSSOM)
# dom-documentorshadowroot-stylesheets

浏览器兼容性