How do you add CSS with Javascript?

前端 未结 14 2628
旧时难觅i
旧时难觅i 2020-11-22 17:18

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

相关标签:
14条回答
  • 2020-11-22 17:57

    Here's a slightly updated version of Chris Herring's solution, taking into account that you can use innerHTML as well instead of a creating a new text node:

    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 );
    }
    
    0 讨论(0)
  • 2020-11-22 18:03

    Shortest One Liner

    // One liner function:
    const addCSS = s =>(d=>{d.head.appendChild(d.createElement("style")).innerHTML=s})(document);
    
    // Usage: 
    addCSS("body{ background:red; }")

    0 讨论(0)
  • 2020-11-22 18:03

    Here's a sample template to help you get started

    Requires 0 libraries and uses only javascript to inject both HTML and CSS.

    The function was borrowed from the user @Husky above

    Useful if you want to run a tampermonkey script and wanted to add a toggle overlay on a website (e.g. a note app for instance)

    // INJECTING THE HTML
    document.querySelector('body').innerHTML += '<div id="injection">Hello World</div>';
    
    // CSS INJECTION FUNCTION
    //https://stackoverflow.com/questions/707565/how-do-you-add-css-with-javascript
    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 );
    }
    
    // INJECT THE CSS INTO FUNCTION
    // Write the css as you normally would... but treat it as strings and concatenate for multilines
    insertCss(
      "#injection {color :red; font-size: 30px;}" +
      "body {background-color: lightblue;}"
    )

    0 讨论(0)
  • 2020-11-22 18:06

    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.

    0 讨论(0)
  • 2020-11-22 18:07

    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);
    }
    
    0 讨论(0)
  • 2020-11-22 18:07

    This easy example of add <style> in head of html

    var sheet = document.createElement('style');
    sheet.innerHTML = "table th{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
    + "table ul {    margin-top: 0 !important;    margin-bottom: 0 !important;}\n"
    + "table td{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
    + ".messages.error{display:none !important;}\n"
    + ".messages.status{display:none !important;} ";
    
    document.body.appendChild(sheet); // append in body
    document.head.appendChild(sheet); // append in head
    

    Source Dynamic style - manipulating CSS with JavaScript

    0 讨论(0)
提交回复
热议问题