How do you read CSS rule values with JavaScript?

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

    Adapted from here, building on scunliffe's answer:

    function getStyle(className) {
        var cssText = "";
        var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
        for (var x = 0; x < classes.length; x++) {        
            if (classes[x].selectorText == className) {
                cssText += classes[x].cssText || classes[x].style.cssText;
            }         
        }
        return cssText;
    }
    
    alert(getStyle('.test'));
    

提交回复
热议问题