How do you read CSS rule values with JavaScript?

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

    I've found none of the suggestions to really work. Here's a more robust one that normalizes spacing when finding classes.

    //Inside closure so that the inner functions don't need regeneration on every call.
    const getCssClasses = (function () {
        function normalize(str) {
            if (!str)  return '';
            str = String(str).replace(/\s*([>~+])\s*/g, ' $1 ');  //Normalize symbol spacing.
            return str.replace(/(\s+)/g, ' ').trim();           //Normalize whitespace
        }
        function split(str, on) {               //Split, Trim, and remove empty elements
            return str.split(on).map(x => x.trim()).filter(x => x);
        }
        function containsAny(selText, ors) {
            return selText ? ors.some(x => selText.indexOf(x) >= 0) : false;
        }
        return function (selector) {
            const logicalORs = split(normalize(selector), ',');
            const sheets = Array.from(window.document.styleSheets);
            const ruleArrays = sheets.map((x) => Array.from(x.rules || x.cssRules || []));
            const allRules = ruleArrays.reduce((all, x) => all.concat(x), []);
            return allRules.filter((x) => containsAny(normalize(x.selectorText), logicalORs));
        };
    })();
    

    Here's it in action from the Chrome console.

    0 讨论(0)
  • 2020-11-21 21:44

    SOLUTION 1 (CROSS-BROWSER)

    function GetProperty(classOrId,property)
    { 
        var FirstChar = classOrId.charAt(0);  var Remaining= classOrId.substring(1);
        var elem = (FirstChar =='#') ?  document.getElementById(Remaining) : document.getElementsByClassName(Remaining)[0];
        return window.getComputedStyle(elem,null).getPropertyValue(property);
    }
    
    alert( GetProperty(".my_site_title","position") ) ;
    

    SOLUTION 2 (CROSS-BROWSER)

    function GetStyle(CLASSname) 
    {
        var styleSheets = document.styleSheets;
        var styleSheetsLength = styleSheets.length;
        for(var i = 0; i < styleSheetsLength; i++){
            if (styleSheets[i].rules ) { var classes = styleSheets[i].rules; }
            else { 
                try {  if(!styleSheets[i].cssRules) {continue;} } 
                //Note that SecurityError exception is specific to Firefox.
                catch(e) { if(e.name == 'SecurityError') { console.log("SecurityError. Cant readd: "+ styleSheets[i].href);  continue; }}
                var classes = styleSheets[i].cssRules ;
            }
            for (var x = 0; x < classes.length; x++) {
                if (classes[x].selectorText == CLASSname) {
                    var ret = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText ;
                    if(ret.indexOf(classes[x].selectorText) == -1){ret = classes[x].selectorText + "{" + ret + "}";}
                    return ret;
                }
            }
        }
    }
    
    alert( GetStyle('.my_site_title') );
    
    0 讨论(0)
  • 2020-11-21 21:44

    I created a version that searches all stylesheets and returns matches as a key/value object. You can also specify startsWith to match child styles.

    getStylesBySelector('.pure-form-html', true);
    

    returns:

    {
        ".pure-form-html body": "padding: 0; margin: 0; font-size: 14px; font-family: tahoma;",
        ".pure-form-html h1": "margin: 0; font-size: 18px; font-family: tahoma;"
    }
    

    from:

    .pure-form-html body {
        padding: 0;
        margin: 0;
        font-size: 14px;
        font-family: tahoma;
    }
    
    .pure-form-html h1 {
        margin: 0;
        font-size: 18px;
        font-family: tahoma;
    }
    

    The code:

    /**
     * Get all CSS style blocks matching a CSS selector from stylesheets
     * @param {string} className - class name to match
     * @param {boolean} startingWith - if true matches all items starting with selector, default = false (exact match only)
     * @example getStylesBySelector('pure-form .pure-form-html ')
     * @returns {object} key/value object containing matching styles otherwise null
     */
    function getStylesBySelector(className, startingWith) {
    
        if (!className || className === '') throw new Error('Please provide a css class name');
    
        var styleSheets = window.document.styleSheets;
        var result = {};
    
        // go through all stylesheets in the DOM
        for (var i = 0, l = styleSheets.length; i < l; i++) {
    
            var classes = styleSheets[i].rules || styleSheets[i].cssRules || [];
    
            // go through all classes in each document
            for (var x = 0, ll = classes.length; x < ll; x++) {
    
                var selector = classes[x].selectorText || '';
                var content = classes[x].cssText || classes[x].style.cssText || '';
    
                // if the selector matches
                if ((startingWith && selector.indexOf(className) === 0) || selector === className) {
    
                    // create an object entry with selector as key and value as content
                    result[selector] = content.split(/(?:{|})/)[1].trim();
                }
            }
        }
    
        // only return object if we have values, otherwise null
        return Object.keys(result).length > 0 ? result : null;
    }
    

    I'm using this in production as part of the pure-form project. Hope it helps.

    0 讨论(0)
  • 2020-11-21 21:46
    function getStyle(className) {
        document.styleSheets.item("menu").cssRules.item(className).cssText;
    }
    getStyle('.test')
    

    Note : "menu" is an element ID which you have applied CSS. "className" a css class name which we need to get its text.

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