Change CSS of class in Javascript?

前端 未结 8 694
春和景丽
春和景丽 2020-12-01 17:53

I\'ve got a class with the display set to none I\'d like to in Javascript now set it to inline I\'m aware I can do this with an id wit

8条回答
  •  無奈伤痛
    2020-12-01 18:36

    You may like to exploit/rewrite this function:

    function getStyleRule(ruleClass, property, cssFile) {
        for (var s = 0; s < document.styleSheets.length; s++) {
            var sheet = document.styleSheets[s];
            if (sheet.href.endsWith(cssFile)) {
                var rules = sheet.cssRules ? sheet.cssRules : sheet.rules;
                if (rules == null) return null;
                for (var i = 0; i < rules.length; i++) {
                    if (rules[i].selectorText == ruleClass) {
                        return rules[i].style[property];
                        //or rules[i].style["border"]="2px solid red";
                        //or rules[i].style["boxShadow"]="4px 4px 4px -2px rgba(0,0,0,0.5)";
                    }
                }
            }
        }
        return null;
    }
    
    • to scan all style sheets attached pass "" as third argument, otherwise something like "index.css"
    • ruleClass contains starting '.'
    • if (rules[i].selectorText && rules[i].selectorText.split(',').indexOf(property) !== -1) condition improvement found here https://stackoverflow.com/a/16966533/881375
    • don't forget to use javascript syntax over css properties, e.g. box-shadow vs. boxShadow

提交回复
热议问题