How do you add CSS with Javascript?

2018-12-31 22:02发布

How do you add CSS rules (eg strong { color: red }) by use of Javascript?

12条回答
情到深处是孤独
2楼-- · 2018-12-31 22:31

This is my solution to add a css rule at the end of the last style sheet list:

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 }");
查看更多
公子世无双
3楼-- · 2018-12-31 22:32

The simple-and-direct approach is to create and add a new style node to the document.

var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = "strong { color: red }";
document.body.appendChild(css);
查看更多
伤终究还是伤i
4楼-- · 2018-12-31 22:32

The solution by Ben Blank wouldn't work in IE8 for me.

However this did work in IE8

function addCss(cssCode) {
var styleElement = document.createElement("style");
  styleElement.type = "text/css";
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = cssCode;
  } else {
    styleElement.appendChild(document.createTextNode(cssCode));
  }
  document.getElementsByTagName("head")[0].appendChild(styleElement);
}
查看更多
何处买醉
5楼-- · 2018-12-31 22:35

You can add classes or style attributes on an element by element basis.

For example:

<a name="myelement" onclick="this.style.color='#FF0';">text</a>

Where you could do this.style.background, this.style.font-size, etc. You can also apply a style using this same method ala

this.className='classname';

If you want to do this in a javascript function, you can use getElementByID rather than 'this'.

查看更多
只若初见
6楼-- · 2018-12-31 22:36

Another option is to use JQuery to store the element's in-line style property, append to it, and to then update the element's style property with the new values. As follows:

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);
        }

And then execute it with the new CSS attributes as an object.

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

This may not necessarily be the most efficient method (I'm open to suggestions on how to improve this. :) ), but it definitely works.

查看更多
孤独寂梦人
7楼-- · 2018-12-31 22:39

YUI just recently added a utility specifically for this. See stylesheet.js here.

查看更多
登录 后发表回答