使用 Javascript 将 CSS 样式表作为字符串注入

新手上路,请多包涵

我正在开发一个 Chrome 扩展程序,我希望用户能够添加自己的 CSS 样式来更改扩展程序页面(而非网页)的外观。我研究过使用 document.stylesheets ,但它似乎希望拆分规则,并且不会让您注入完整的样式表。有没有一种解决方案可以让我使用字符串在页面上创建新的样式表?

我目前没有使用 jQuery 或类似的工具,因此最好使用纯 Javascript 解决方案。

原文由 Dan Hlavenka 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 348
2 个回答

有几种方法可以做到这一点,但最简单的方法是创建一个 <style> 元素,设置其 textContent 属性,然后附加到页面的 <head>

 /**
 * Utility function to add CSS in multiple passes.
 * @param {string} styleString
 */
function addStyle(styleString) {
  const style = document.createElement('style');
  style.textContent = styleString;
  document.head.append(style);
}

addStyle(`
  body {
    color: red;
  }
`);

addStyle(`
  body {
    background: silver;
  }
`);

如果需要,您可以稍微更改它,以便在调用 addStyle() 时替换 CSS,而不是附加它。

 /**
 * Utility function to add replaceable CSS.
 * @param {string} styleString
 */
const addStyle = (() => {
  const style = document.createElement('style');
  document.head.append(style);
  return (styleString) => style.textContent = styleString;
})();

addStyle(`
  body {
    color: red;
  }
`);

addStyle(`
  body {
    background: silver;
  }
`);

IE 编辑: 请注意 IE9 及以下版本 最多只允许 32 个样式表,因此在使用第一个代码段时要小心。在 IE10 中,该数字增加到 4095。

2020 年编辑: 这个问题很老了,但我仍然偶尔会收到有关它的通知,所以我更新了代码,使其更现代一些,并将 .innerHTML 替换为 .textContent 。这个特定实例是安全的,但尽可能避免 innerHTML 是一个好习惯,因为它可能是 XSS 攻击向量。

原文由 Liam Newmarch 发布,翻译遵循 CC BY-SA 4.0 许可协议

多亏了 这个人,我才能找到正确的答案。这是它是如何完成的:

 function addCss(rule) {
  let css = document.createElement('style');
  css.type = 'text/css';
  if (css.styleSheet) css.styleSheet.cssText = rule; // Support for IE
  else css.appendChild(document.createTextNode(rule)); // Support for the rest
  document.getElementsByTagName("head")[0].appendChild(css);
}

// CSS rules
let rule  = '.red {background-color: red}';
    rule += '.blue {background-color: blue}';

// Load the rules and execute after the DOM loads
window.onload = function() {addCss(rule)};

小提琴

原文由 John R Perry 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题