var flag = true; if (flag) { loadStyles('basic.css'); } function loadStyles(url) { var link = document.createElement('link');link.rel = 'stylesheet'; link.type = 'text/css'; link.href = url; document.getElementsByTagName('head')[0].appendChild(link); }
动态执行 style
代码如下:
<script type="text/javascript"> var flag = true; if (flag) { var style = document.createElement('style'); style.type = 'text/css'; //var box= document.createTextNode('#box{background:red}');// IE6,7,8 不支持 //style.appendChild(box); document.getElementsByTagName('head')[0].appendChild(style); insertRule(document.styleSheets[0], '#box', 'background:red', 0); } function insertRule(sheet, selectorText, cssText, position) { //如果是非 IE6,7,8 if (sheet.insertRule) { sheet.insertRule(selectorText + "{" + cssText + "}", position); //如果是 IE6,7,8 } else if (sheet.addRule) { sheet.addRule(selectorText, cssText, position); } } </script>