使用创建style的方式
btn.addEventListener("click", async () => {
const ns = document.createElement("style");
ns.textContent = `
button {
color: red;
}
`;
document.head.append(ns);
ns.sheet.addRule("p", "color: green");
});
使用CSSStyleSheet
btn.addEventListener("click", async () => {
const sheet = new CSSStyleSheet();
sheet.replaceSync("button { color: red; }");
sheet.addRule("p", "color: green");
document.adoptedStyleSheets = [sheet];
});
See also: