How do you read CSS rule values with JavaScript?

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

提交回复
热议问题