Creating a CSS class in jQuery

前端 未结 4 2139
[愿得一人]
[愿得一人] 2020-12-04 14:37

I believe the .addClass() function in jQuery attaches a CSS class to the current selection, but I was wondering I could create or define a CSS class in jQuery, and then atta

4条回答
  •  执念已碎
    2020-12-04 15:18

    Here's something that will create a CSS class that will be available everywhere and apply it to a jQuery object. This uses the same basic technique as mentioned by MooGoo but is fleshed out into a fully functional piece of code:

    (function() {
        var addRule;
    
        if (typeof document.styleSheets != "undefined" && document.styleSheets) {
            addRule = function(selector, rule) {
                var styleSheets = document.styleSheets, styleSheet;
                if (styleSheets && styleSheets.length) {
                    styleSheet = styleSheets[styleSheets.length - 1];
                    if (styleSheet.addRule) {
                        styleSheet.addRule(selector, rule)
                    } else if (typeof styleSheet.cssText == "string") {
                        styleSheet.cssText = selector + " {" + rule + "}";
                    } else if (styleSheet.insertRule && styleSheet.cssRules) {
                        styleSheet.insertRule(selector + " {" + rule + "}", styleSheet.cssRules.length);
                    }
                }
            }
        } else {
            addRule = function(selector, rule, el, doc) {
                el.appendChild(doc.createTextNode(selector + " {" + rule + "}"));
            };
        }
    
        var createCssClass = function(className, cssProps, doc) {
            doc = doc || document;
    
            var head = doc.getElementsByTagName("head")[0];
            if (head && addRule) {
                var selector = "*." + className;
                var ruleBits = [];
                for (var i in cssProps) {
                    if (cssProps.hasOwnProperty(i)) {
                        ruleBits.push(i + ":" + cssProps[i] + ";");
                    }
                }
                var rule = ruleBits.join("");
                var styleEl = doc.createElement("style");
                styleEl.type = "text/css";
                styleEl.media = "screen";
                head.appendChild(styleEl);
                addRule(selector, rule, styleEl, doc);
                styleEl = null;
            }
        };
    
        jQuery.fn.createAndApplyCssClass = function(className, cssProps) {
            createCssClass(className, cssProps, document);
            this.addClass(className);
        };
    })();
    
    $("#someelement").createAndApplyCssClass("test", {
        "background-color": "green",
        "color" : "white"
    });
    

提交回复
热议问题