How do you add CSS with Javascript?

前端 未结 14 2746
旧时难觅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 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.

提交回复
热议问题