日期:2014-05-16  浏览次数:20714 次

js动态加载css文件

?

function addStyle(stylePath) {
??????????????? var container = document.getElementsByTagName("head")[0];
??????????????? var addStyle = document.createElement("link");
??????????????? addStyle.rel = "stylesheet";
??????????????? addStyle.type = "text/css";
??????????????? addStyle.media = "screen";
??????????????? addStyle.href = stylePath;
??????????????? container.appendChild(addStyle);
??????????? }
??????????? addStyle('css/add.css');

?

?

document.getElementById("elementId").style.background="#ff0000";

?

document.getElementsByTagName("a")[0].style.cssText = "background:#ff0000;border:1px #dfdfdf solid;";

?

link对象可以加id

<link id="loadCss" type="text/css" rel="stylesheet" href="bj.css"/>

var cssTag = document.getElementById('loadCss');

var?filesadded=""?//保存已经绑定文件名字的字符串?
function?checkloadjscssfile(filename,?filetype){?
if?(filesadded.indexOf("["+filename+"]")==-1){//?indexOf判断数组里是否有某一项?
??loadjscssfile(filename,?filetype)?
??filesadded+="["+filename+"]"?//把文件名字添加到filesadded?
}?

?

?filesAdded : {},
this.filesAdded[href] = true;

?

?var links=document.getElementsByTagName("link");? //得到所有的link对象集合
?? for(i=0;i<links.length;i++)??????? //依次判断每个link对象
?? {
??? if(links[i].href && links[i].href.indexOf(src)!=-1)
??? {
???? if(links[i].readyState=="loaded" || links[i].readyState=="complete" || links[i].readyState=="interactive")
???? {
????? isLoaded=true;
????? break;
???? }
??? }
?? }