How do you read CSS rule values with JavaScript?

后端 未结 16 1153
天涯浪人
天涯浪人 2020-11-21 21:02

I would like to return a string with all of the contents of a CSS rule, like the format you\'d see in an inline style. I\'d like to be able to do this without knowing what i

16条回答
  •  甜味超标
    2020-11-21 21:27

    Have adapted julmot's answer in order to get a more complete result. This method will also return styles where the class is part for the selector.

    //Get all styles where the provided class is involved
    //Input parameters should be css selector such as .myClass or #m
    //returned as an array of tuples {selectorText:"", styleDefinition:""}
    function getStyleWithCSSSelector(cssSelector) {
        var styleSheets = window.document.styleSheets;
        var styleSheetsLength = styleSheets.length;
        var arStylesWithCSSSelector = [];
    
        //in order to not find class which has the current name as prefix
        var arValidCharsAfterCssSelector = [" ", ".", ",", "#",">","+",":","["];
    
        //loop through all the stylessheets in the bor
        for(var i = 0; i < styleSheetsLength; i++){
            var classes = styleSheets[i].rules || styleSheets[i].cssRules;
            var classesLength = classes.length;
            for (var x = 0; x < classesLength; x++) {
                //check for any reference to the class in the selector string
                if(typeof classes[x].selectorText != "undefined"){
                    var matchClass = false;
    
                    if(classes[x].selectorText === cssSelector){//exact match
                        matchClass=true;
                    }else {//check for it as part of the selector string
                        //TODO: Optimize with regexp
                        for (var j=0;j

    In addition, I've made a function which collects the css style definitions to the sub-tree of a root node your provide (through a jquery selector).

    function getAllCSSClassDefinitionsForSubtree(selectorOfRootElement){
        //stack in which elements are pushed and poped from
        var arStackElements = [];
        //dictionary for checking already added css class definitions
        var existingClassDefinitions = {}
    
        //use jquery for selecting root element
        var rootElement = $(selectorOfRootElement)[0];
        //string with the complete CSS output
        var cssString = "";
    
        console.log("Fetching all classes used in sub tree of " +selectorOfRootElement);
        arStackElements.push(rootElement);
        var currentElement;
    
        while(currentElement = arStackElements.pop()){
            currentElement = $(currentElement);
            console.log("Processing element " + currentElement.attr("id"));
    
            //Look at class attribute of element 
            var classesString = currentElement.attr("class");
            if(typeof classesString != 'undefined'){
                var arClasses = classesString.split(" ");
    
                //for each class in the current element
                for(var i=0; i< arClasses.length; i++){
    
                    //fetch the CSS Styles for a single class. Need to append the . char to indicate its a class
                    var arStylesWithCSSSelector = getStyleWithCSSSelector("."+arClasses[i]);
                    console.log("Processing class "+ arClasses[i]);
    
                    if(arStylesWithCSSSelector != null){
                        //console.log("Found "+ arStylesWithCSSSelector.length + " CSS style definitions for class " +arClasses[i]);
                        //append all found styles to the cssString
                        for(var j=0; j< arStylesWithCSSSelector.length; j++){
                            var tupleStyleWithCSSSelector = arStylesWithCSSSelector[j];
    
                            //check if it has already been added
                            if(typeof existingClassDefinitions[tupleStyleWithCSSSelector.selectorText] === "undefined"){
                                //console.log("Adding " + tupleStyleWithCSSSelector.styleDefinition);
                                cssString+= tupleStyleWithCSSSelector.styleDefinition;
                                existingClassDefinitions[tupleStyleWithCSSSelector.selectorText] = true;
                            }else {
                                //console.log("Already added " + tupleStyleWithCSSSelector.styleDefinition);
                            }
                        }
                    }
                }
            }
            //push all child elments to stack
            if(currentElement.children().length>0){
                arStackElements= arStackElements.concat(currentElement.children().toArray());
            }
        }
    
        console.log("Found " + Object.keys(existingClassDefinitions).length + " CSS class definitions");
        return cssString;
    }
    

    Note that if a class is defined several times with the same selector, the above function will only pick up the first. Note that the example uses jQuery (but cab relatively easily be rewritten to not use it)

提交回复
热议问题