js动态添加CSS

(function() {
      var isLoaded = false;
      AddStyle = function(rules) {
        var styleElement = document.createElement('style');
        styleElement.type = 'text/css';
        if ( $IE ) {   //判断IE浏览器
          styleElement.styleSheet.cssText = rules;
        }
        else {
          var frag = document.createDocumentFragment();
          frag.appendChild(document.createTextNode(rules));
          styleElement.appendChild(frag);
        }
        function append() {
          document.getElementsByTagName('head')[0].appendChild(styleElement);
        }
		//IE 无法取到document
        if (!$IE || isLoaded) { 
          append();
        }
        else {
          window.attachEvent('onload', function() {
            isLoaded = true;
            append();
          });
        }
      };
	  })();

用法:

AddStyle('body { color: #CCC; }')
原文地址:https://www.cnblogs.com/feng_013/p/1807520.html