与动态脚本类似,所谓动态样式是指在页面刚加载时不存在的样式;动态样式是在页面加载完成后动态添加到页面中。
我们以下面这个典型的元素为例:
使用DOM代码可以很容易的动态创建出这个元素:
var link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = "style.css";
var head = document.getElementsByTagName("head")[0];
head.appendChild(link);
以上代码在所有主流浏览器中都可以正常运行。需要注意的是,必须将元素添加到
而不是元素,才能保证在所有浏览器中的行为一致。整个过程可以用一下函数来表示:function loadStyles(url) {
var link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = url;
var head = document.getElementsByTagName("head")[0];
head.appendChild(link);
}
loadStyles("style.css")
加载外部样式文件的过程是异步的,也就是加载样式与执行JavaScript代码的过程没有固定的次序。
另一种定义样式的方式是使用
body { background-color: red; }
按照相同的逻辑,下列DOM代码应该是有效的:
var style = document.createElement("style");
style.type = "text/css";
style.appendChild(document.createTextNode("body{background-color:red;}"));
var head = document.getElementsByTagName("head")[0];
head.appendChild(style);
以上代码可以在Firefox、Safrai、Chrome和Opera中运行,在IE中则会报错。IE将
var style = document.createElement("style");
style.type = "text/css";
try {
style.appendChild(document.createTextNode("body{background-color:red}"));
} catch (ex) {
style.styleSheet.cssText = "body{background-color:red}";
}
var head = document.getElementsByTagName("head")[0];
head.appendChild(style);
与动态添加嵌入式脚本类似,重写后的代码使用了try-catch语句来捕获IE抛出的错误,然后再使用针对IE的特殊方式来设置样式。一次通用的解决方案如下:
function loadStyleString(css) {
var style = document.createElement("style");
style.type = "text/css";
try {
style.appendChild(document.createTextNode(css));
} catch (ex) {
style.styleSheet.cssText = css;
}
var head = document.getElementsByTagName("head")[0];
head.appendChild(style);
}
loadStyleString("body{background-color:red}");