How do you read CSS rule values with JavaScript?

后端 未结 16 1370
天涯浪人
天涯浪人 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:30

    Since the accepted answer from "nsdel" is only avilable with one stylesheet in a document this is the adapted full working solution:

        /**
         * Gets styles by a classname
         * 
         * @notice The className must be 1:1 the same as in the CSS
         * @param string className_
         */
        function getStyle(className_) {
    
            var styleSheets = window.document.styleSheets;
            var styleSheetsLength = styleSheets.length;
            for(var i = 0; i < styleSheetsLength; i++){
                var classes = styleSheets[i].rules || styleSheets[i].cssRules;
                if (!classes)
                    continue;
                var classesLength = classes.length;
                for (var x = 0; x < classesLength; x++) {
                    if (classes[x].selectorText == className_) {
                        var ret;
                        if(classes[x].cssText){
                            ret = classes[x].cssText;
                        } else {
                            ret = classes[x].style.cssText;
                        }
                        if(ret.indexOf(classes[x].selectorText) == -1){
                            ret = classes[x].selectorText + "{" + ret + "}";
                        }
                        return ret;
                    }
                }
            }
    
        }
    

    Notice: The selector must be the same as in the CSS.

提交回复
热议问题