如何使用Javascript添加CSS规则(如强{颜色:红色})?


当前回答

如果你知道页面中至少存在一个<style>标签,使用这个函数:

CSS=function(i){document.getElementsByTagName('style')[0].innerHTML+=i};

用法:

CSS("div{background:#00F}");

其他回答

这是我在最后一个样式表列表的末尾添加css规则的解决方案:

var css = new function()
{
    function addStyleSheet()
    {
        let head = document.head;
        let style = document.createElement("style");

        head.appendChild(style);
    }

    this.insert = function(rule)
    {
        if(document.styleSheets.length == 0) { addStyleSheet(); }

        let sheet = document.styleSheets[document.styleSheets.length - 1];
        let rules = sheet.rules;

        sheet.insertRule(rule, rules.length);
    }
}

css.insert("body { background-color: red }");

你也可以使用DOM Level 2 CSS接口(MDN):

var sheet = window.document.styleSheets[0];
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);

...除了IE8和更早的版本,它使用了自己略微不同的措辞:

sheet.addRule('strong', 'color: red;', -1);

与createElement-set-innerHTML方法相比,这种方法有一个理论上的优势,因为您不必担心在innerHTML中放入特殊的HTML字符,但实际上样式元素是遗留HTML中的CDATA,而且' < '和' & '很少在样式表中使用。

在开始像这样向它追加内容之前,确实需要一个样式表。这可以是任何现有的活动样式表:外部的、嵌入式的或空的,这都没有关系。如果没有,目前创建它的唯一标准方法是使用createElement。

这是Chris Herring的解决方案的一个稍微更新的版本,考虑到你也可以使用innerHTML,而不是创建一个新的文本节点:

function insertCss( code ) {
    var style = document.createElement('style');
    style.type = 'text/css';

    if (style.styleSheet) {
        // IE
        style.styleSheet.cssText = code;
    } else {
        // Other browsers
        style.innerHTML = code;
    }

    document.getElementsByTagName("head")[0].appendChild( style );
}

YUI最近专门为此添加了一个实用程序。点击这里查看stylesheet.js。

另一种选择是使用JQuery存储元素的内联样式属性,然后附加到它,然后用新值更新元素的样式属性。如下:

function appendCSSToElement(element, CssProperties)
        {
            var existingCSS = $(element).attr("style");

             if(existingCSS == undefined) existingCSS = "";

            $.each(CssProperties, function(key,value)
            {
                existingCSS += " " + key + ": " + value + ";";
            });

            $(element).attr("style", existingCSS);

            return $(element);
        }

然后用新的CSS属性作为对象执行它。

appendCSSToElement("#ElementID", { "color": "white", "background-color": "green", "font-weight": "bold" });

这可能不是最有效的方法(我愿意接受关于如何改进这一点的建议。:)),但它绝对有效。