StyleSheetList

Baseline 已广泛支持

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

StyleSheetList 接口表示一个 CSSStyleSheet 对象列表。此对象的实例可以由 Document.styleSheets 返回。

它是一个类数组对象,但不能使用 Array 方法进行迭代。但是,它可以通过标准 for 循环按索引进行迭代,或者转换为一个 Array

注意: 通常像 StyleSheetList 这样的列表接口会包装 Array 类型,因此您可以在它们上使用 Array 方法。出于 历史原因,这里的情况并非如此。但是,您可以将 StyleSheetList 转换为 Array 以便使用这些方法(请参见下面的示例)。

实例属性

StyleSheetList.length 只读

返回集合中 CSSStyleSheet 对象的数量。

实例方法

StyleSheetList.item()

返回指定索引处的 CSSStyleSheet 对象,如果该索引没有项,则返回 null

示例

使用 for 循环获取 CSSStyleSheet 对象

js
for (const styleSheet of document.styleSheets) {
  console.log(styleSheet); // A CSSStyleSheet object
}

使用 Array 方法获取文档的所有 CSS 规则

js
const allCSS = [...document.styleSheets]
  .map((styleSheet) => {
    try {
      return [...styleSheet.cssRules].map((rule) => rule.cssText).join("");
    } catch (e) {
      console.log(
        "Access to stylesheet %s is denied. Ignoring…",
        styleSheet.href,
      );
      return undefined;
    }
  })
  .filter(Boolean)
  .join("\n");

规范

规范
CSS 对象模型 (CSSOM)
# the-stylesheetlist-interface

浏览器兼容性