You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

创建HTMLStyleElement后sheet属性始终为null,如何枚举CSS规则?

解决HTMLStyleElement.sheet为null无法枚举CSS规则的问题

问题根源

你创建的<style>元素没有被插入到DOM树中,浏览器只会为已挂载到DOM的style元素生成对应的CSSStyleSheet对象,未插入DOM的style元素其sheet属性会一直是null。

修改方案

把创建好的style元素先插入到document.head或document.body中,之后再访问sheet属性就能正常获取样式规则了。如果不想让这段CSS影响页面样式,可以在枚举完规则后立即移除该元素。

修改后的代码

let css: HTMLStyleElement = document.createElement("style");
let cssTxt = 'div {border: 2px solid black; background-color: blue;} @font-face { font-family: Roboto; font-style: normal; font-weight: 700; src: url(roboto-v18-latin_latin-ext-700.53950ed05f8532ac.eot); src: local("Roboto Bold"),local("Roboto-Bold"),url(roboto-v18-latin_latin-ext-700.53950ed05f8532ac.eot?#iefix) format("embedded-opentype"),url(roboto-v18-latin_latin-ext-700.9d541330b4ce7057.woff2) format("woff2"),url(roboto-v18-latin_latin-ext-700.c52f983fe85258f7.woff) format("woff"),url(roboto-v18-latin_latin-ext-700.8d9b6be89e992a10.ttf) format("truetype"),url(roboto-v18-latin_latin-ext-700.4cf5420d5ce6b793.svg#Roboto) format("svg")}';

css.innerHTML = cssTxt;
// 先插入到DOM中
document.head.appendChild(css);

try {
    // 现在可以正常访问sheet和cssRules了
    for (const rule of css.sheet?.cssRules || []) {
        if (rule.constructor.name === "CSSFontFaceRule") { // 替换成你需要的规则类型名
            console.log(rule.cssText);
        }
    }
} finally {
    // 可选:移除元素,避免影响页面样式
    document.head.removeChild(css);
}

补充说明

如果你只是想解析CSS文本而不需要挂载到DOM,也可以直接使用CSSStyleSheet构造函数创建样式表,这种方式更简洁:

const sheet = new CSSStyleSheet();
sheet.replaceSync(cssTxt);
for (const rule of sheet.cssRules) {
    // 你的规则筛选逻辑
}

内容的提问来源于stack exchange,提问作者user1470240

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 11:00:59