簡體   English   中英

如何動態更新head標簽中的CSS樣式

[英]How to update the CSS style in head tag dynamically

我有一個如下的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。

但是我也想用限制來修改樣式標簽數據。

我期望下面的行將更新樣式標簽中的數據。

rules[r].selectorText = selectorAppender + selectorText;

請幫助我解決此問題。

很難! =)

我這樣修改了您的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

阿波羅

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM