html动态加载css样式和js脚本示例

2019-01-15 11:16:41于丽

<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>