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

使用`all: unset`与cssText时CSS声明顺序错误导致样式失效的问题求助

all: unset与cssText时CSS声明顺序错误导致样式失效的问题求助

我现在碰到一个棘手的问题:我正在尝试把主文档头部的样式复制到画中画(Picture-in-Picture)窗口里,我们的应用用了Stitches JS,它是直接操作CSSOM的,所以我得把StyleSheetList里的所有样式都复制过去——大部分情况都正常,但遇到all: unset的时候就出问题了:它会被展开成所有的CSS声明,而且顺序完全不对,导致我后续设置的样式被覆盖掉。我全程都是在Chrome里测试的。

举个例子,我原本写的CSS是这样的:

button {
  all: unset;
  border-radius: 12px;
}

但复制之后就变成了这个样子:

button {
...
 block-size: unset;
 border-block: unset;
 border: unset;
 border-radius: 12px;                  /* 这里设置了border-radius */
 border-collapse: unset;
 border-end-end-radius: unset;         /* 但这里又把它unset了 */
 border-end-start-radius: unset;
 border-inline: unset;
 border-start-end-radius: unset;
 border-start-start-radius: unset;
...
}

我用来复制样式的简化代码是这样的:

[...document.styleSheets].forEach((styleSheet) => {
  try {
    const style = document.createElement("style");
    style.textContent = [...styleSheet.cssRules].map(({cssText}) => cssText).join("");
    pipDocument.head.appendChild(style);
  } catch (e) {}
});

你可以看这个示例代码复现这个问题:

JavaScript代码

const styleEl = document.createElement("style");
document.head.appendChild(styleEl);
const sheet = styleEl.sheet;
sheet.insertRule(
  ".test1 { all: unset; background-color: lightblue; border-radius: 12px; padding: 12px; }",
  sheet.cssRules.length
);

const allCSS = [...document.styleSheets]
  .map((styleSheet) => {
    try {
      return [...styleSheet.cssRules].map((rule) => rule.cssText).join("");
    } catch (e) {}
  })
  .filter(Boolean)
  .join("\n");
  
const modifiedCSS = allCSS.replace(".test1", ".test2");

const newStyleEl = document.createElement("style");
newStyleEl.innerHTML = modifiedCSS;
document.head.appendChild(newStyleEl);

const divElement = document.createElement("div");
divElement.innerHTML = `<pre>${allCSS}</pre>`;
document.body.appendChild(divElement);

HTML代码

<!DOCTYPE html>
<html lang="en">
  <head>
  
  </head>
  <body>
    <div class="test1">test</div>
    <div class="test2">test copied</div>
    <script src="index.js"></script>
  </body>
</html>

备注:内容来源于stack exchange,提问作者Dawe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 12:58:03