js 动态构建style

使用创建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:

posted @ 2020-10-11 12:16  Ajanuw  阅读(194)  评论(0编辑  收藏  举报