Inject CSS stylesheet as string using Javascript

后端 未结 4 1260
一整个雨季
一整个雨季 2020-11-30 01:37

I\'m developing a Chrome extension, and I\'d like users to be able to add their own CSS styles to change the appearance of the extension\'s pages (not web pages). I\'ve look

4条回答
  •  自闭症患者
    2020-11-30 02:31

    Thanks to this guy, I was able to find the correct answer. Here's how it's done:

    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)};
    

    fiddle

提交回复
热议问题