如何动态更新head标签中的CSS样式

时间:2014-04-30 08:31:56

标签: javascript html css

我有一个HTML,如下所示

<!DOCTYPE html>
<html>
    <head>
        <style>
            p{font-size:14pt;color:red;}
        </style>
    </head>
    <body>
        <div>
            <p class="hello"> this is a p tag </p>
            <p> this is a p without class defined</p>
            <div> this is a div tag 
                <p> this is a p tag within the div</p>
            </div>
        </div>
        <div id = "OriginalMail" class = "orgmail">
            <p> this is a Original Mail</p>
            <p class="hello"> this is a p tag </p>
            <p> this is a p without class defined</p>
            <div> this is a div tag 
                <p> this is a p tag within the div</p>
            </div>
        </div>
    </body>
</html>

我正在使用javascript函数将样式限制为仅应用于具有类名orgmail的div。

var sheets = document.styleSheets;
var OriginalMail = document.getElementById("OriginalMail");
var className = OriginalMail.className;
var selectorAppender = "div." + className +  " ";
for (var i in sheets) {
    var rules = sheets[i].rules || sheets[i].cssRules;
    for (var r in rules) {
        var selectorText = rules[r].selectorText;
        if(typeof selectorText !== "undefined") {
            rules[r].selectorText = selectorAppender + selectorText;
        }
    }
}

该样式仅应用于具有类名的div。

但我想修改Style标签数据也有限制。

我原以为下面一行会更新样式标记中的数据。

rules[r].selectorText = selectorAppender + selectorText;

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

很难! =)

我修改了你的JS:

var sheets = document.styleSheets;
var OriginalMail = document.getElementById("OriginalMail");
var className = OriginalMail.className;
var selectorAppender = "div." + className +  " ";
for (var i in sheets) {
    var rules = sheets[i].cssRules;
    for (var r in rules) {
        if(typeof rules[r] === "object") {
            var selectorText = rules[r].selectorText;
            var style = rules[r].style.cssText;
            if(typeof selectorText !== "undefined") {
                sheets[i].deleteRule(rules[r]);
                var rule = selectorAppender + selectorText + " {" + style + " }";
                sheets[i].insertRule(rule,0);            
            }
        }
    }
}

css规则的许多属性都是只读的,因此您必须删除规则并添加新的CSS规则。

我制作了JSFiddle

阿波罗