这种方式在各个主流浏览器存在兼容性问题,像firefox等标准浏览器无法直接获取设置styleSheet的cssText值,标准浏览器下只能使用document.styleSheets[0].cssRules[0].cssText单个获取样式;
同时使用:document.styleSheets[0].cssRules[0].cssText=newcssText;页面不会自动更新样式,必须使用:document.styleSheets[0].cssRules[0].style.cssText=newcssText;
这点似乎没坑爹的IE来的
function includeStyleElement(styles,styleId) {
if (document.getElementById(styleId)) { return }
var style = document.createElement("style");
style.id = styleId; //这里最好给ie设置下面的属性 /*
if (isIE())
{ style.type = "text/css"; style.media = "screen" }*/
(document.getElementsByTagName("head")[0] || document.body).appendChild(style);
if (style.styleSheet)
{ //for ie style.styleSheet.cssText = styles; }
else {//for w3c style.appendChild(document.createTextNode(styles)); }
}
var styles = "#div{background-color: #FF3300; color:#FFFFFF }"; includeStyleElement(styles,"newstyle");
人性化和简便。YUI中使用了一个很好的办法:style.appendChild(document.createTextNode(styles));采用createTextNode将样式字符串添加到<style>标签内;