How do you read CSS rule values with JavaScript?

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

提交回复
热议问题