样式(css)文件,一般情况之下,是在创建网页时,就部署好了。但在动态化的环境之下,动态加载样式是必要的开发方式。
动态加载css样式有两种方式:
1、动态插入css外部文件的方法:function loadStyle(url){
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = url;
var head = document.getElementsByTagName('head')[0];
head.appendChild(link);
}
loadStyle('test.css');
2、动态加载css代码片段function loadCssCode(code){
var style = document.createElement('style');
style.type = 'text/css';
style.rel = 'stylesheet';
try{
//for Chrome Firefox Opera Safari
style .appendChild(document.createTextNode(code));
}catch(ex){
//for IE
style.styleSheet.cssText = code;
}
var head = document.getElementsByTagName('head')[0];
head.appendChild(style);
}
loadCssCode('body{background-color:#f00}');