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

怎么能动态增加和删除样式??
就是能增加 <link   href= "2873.files/css/main.css "   rel= "stylesheet "   type= "text/css "   id= "cmsstyle "/>
和删除上面引用样式的语句?用js可以做到吗?高手指点

------解决方案--------------------
参考
http://www.purewhite.cn/2006/07/10/active-style-sheet/
------解决方案--------------------
<script type= "text/javascript ">
<!--
function getStyleSheet(index)
{
if (typeof index == 'undefined ')
index = 0;
if (index < 0)
index = document.styleSheets.length + index;
if (typeof document.styleSheets == 'undefined ' || index < 0 || index > = document.styleSheets.length)
return null;

var style = document.styleSheets[index];

return StyleSheet_makeCompatible(style);
}

//var style = getStyleSheet(0);
//var style2 = getStyleSheet(-1);

function addStyleSheet(url)
{
var style;
if (typeof url == 'undefined ')
{
style = document.createElement( 'style ');
}
else
{
style = document.createElement( 'link ');
style.rel = 'stylesheet ';
style.type = 'text/css ';
style.href = url;
}
document.getElementsByTagName( 'head ')[0].appendChild(style);

style = document.styleSheets[document.styleSheets.length - 1];

return StyleSheet_makeCompatible(style);
}

//var style = addStyleSheet();
//var style2 = addStyleSheet( '/styles/additional_style.css ');

function StyleSheet_makeCompatible(style)
{
try
{
style.cssRules;
}
catch (e)
{
return style;
}
if (typeof style.cssRules == 'undefined ' && typeof style.rules != 'undefined ')
style.cssRules = style.rules;
if (typeof style.insertRule == 'undefined ' && typeof style.addRule != 'undefined ')
style.insertRule = StyleSheet_insertRule;
if (typeof style.deleteRule == 'undefined ' && typeof style.removeRule != 'undefined ')
style.deleteRule = style.removeRule;
if (typeof style.cssRules == 'undefined ' || typeof style.insertRule == 'undefined ' || typeof style.deleteRule == 'undefined ')
return null;
else
return style;
}

function StyleSheet_insertRule(rule, index)
{
if (rule.match(/^([^{]+)\{(.*)\}\s*$/))
{
this.addRule(RegExp.$1, RegExp.$2, index);
return index;
}
throw "Syntax error in CSS rule to be added ";
}

//var style = addStyleSheet();
//style.insertRule( 'div {color: blue} ', style.cssRules.length);
//style.insertRule( 'div#special {color: red} ', 0);
//alert(style.cssRules.length);

//var style2 = getStyleSheet(0);
//style2.removeRule(0);
//style2.removeRule(style2.cssRules.length - 1);
</script>
------解决方案--------------------
http://community.csdn.net/Expert/topic/5534/5534514.xml?temp=.3409998
可以参考一下
------解决方案--------------------
document.getElementsByTagName( 'head ')[0].removeChild(document.getElementsByTagName( 'head ')[0].childNodes[0]);
------解决方案--------------------
http://community.csdn.net/Expert/topic/5534/5534514.xml?temp=.3409998