你如何用JavaScript阅读CSS规则值?

Dio*_*ane 106 html javascript css

我想返回一个包含CSS规则所有内容的字符串,就像您在内联样式中看到的格式一样.我希望能够在不知道特定规则中包含的内容的情况下执行此操作,因此我不能仅通过样式名称将其拉出(如.style.width等)

CSS:

.test {
    width:80px;
    height:50px;
    background-color:#808080;
}
Run Code Online (Sandbox Code Playgroud)

到目前为止的代码:

function getStyle(className) {
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
    for(var x=0;x<classes.length;x++) {
        if(classes[x].selectorText==className) {
            //this is where I can collect the style information, but how?
        }
    }
}
getStyle('.test')
Run Code Online (Sandbox Code Playgroud)

小智 81

改编自这里,建立在scunliffe的回答:

function getStyle(className) {
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
    for (var x = 0; x < classes.length; x++) {
        if (classes[x].selectorText == className) {
            (classes[x].cssText) ? alert(classes[x].cssText) : alert(classes[x].style.cssText);
        }
    }
}
getStyle('.test');
Run Code Online (Sandbox Code Playgroud)

  • 如果有多个样式表,那么你也需要循环遍历那些样式表.for(var i = 0; i <document.styleSheets.length; i ++){var s = document.styleSheets [i];} (13认同)
  • 请注意,className必须与CSS文件中使用的选择器完全匹配.例如,如果样式被描述为".article a,article a:hover {color:#ccc;}",则getStyle(".article a")将找不到任何内容. (10认同)
  • 这在 chrome 中不起作用,但在 firefox 中起作用,可能是什么问题? (2认同)
  • @Johnydep`var classes`应该是Chrome中的`document.styleSheets [0] .rules [0] .cssRules`.这可以(创造性地)添加到答案中的垫片中. (2认同)

dud*_*ude 22

由于"nsdel"中接受的答案仅适用于文档中的一个样式表,因此这是经过调整的完整工作解决方案:

    /**
     * Gets styles by a classname
     * 
     * @notice The className must be 1:1 the same as in the CSS
     * @param string className_
     */
    function getStyle(className_) {

        var styleSheets = window.document.styleSheets;
        var styleSheetsLength = styleSheets.length;
        for(var i = 0; i < styleSheetsLength; i++){
            var classes = styleSheets[i].rules || styleSheets[i].cssRules;
            if (!classes)
                continue;
            var classesLength = classes.length;
            for (var x = 0; x < classesLength; x++) {
                if (classes[x].selectorText == className_) {
                    var ret;
                    if(classes[x].cssText){
                        ret = classes[x].cssText;
                    } else {
                        ret = classes[x].style.cssText;
                    }
                    if(ret.indexOf(classes[x].selectorText) == -1){
                        ret = classes[x].selectorText + "{" + ret + "}";
                    }
                    return ret;
                }
            }
        }

    }
Run Code Online (Sandbox Code Playgroud)

注意:选择器必须与CSS中的相同.

  • 如果样式表没有规则或cssRules(可能发生!),你的代码就会失败.添加if(!classes)继续; 在var classes = styleSheets [i] .rules ||之后 样式表[I] .cssRules; var classesLength = classes.length; 看我的编辑 (3认同)

T.T*_*dua 16

解决方案1(交叉浏览器)

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") ) ;
Run Code Online (Sandbox Code Playgroud)

解决方案2(交叉浏览器)

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') );
Run Code Online (Sandbox Code Playgroud)


Lar*_*nal 6

一些浏览器差异需要注意:

鉴于CSS:

div#a { ... }
div#b, div#c { ... }
Run Code Online (Sandbox Code Playgroud)

在InsDel的例子中,类将在FF中2个类,在IE7中有3个类.

我的例子说明了这一点

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <style>
    div#a { }
    div#b, div#c { }
    </style>
    <script>
    function PrintRules() {
    var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules
        for(var x=0;x<rules.length;x++) {
            document.getElementById("rules").innerHTML += rules[x].selectorText + "<br />";
        }
    }
    </script>
</head>
<body>
    <input onclick="PrintRules()" type="button" value="Print Rules" /><br />
    RULES:
    <div id="rules"></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)


Der*_*mba 5

我发现没有任何建议可以真正起作用。这是一个更强大的方法,可以在查找类时规范间距。

//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));
    };
})();
Run Code Online (Sandbox Code Playgroud)

这是 Chrome 控制台中的操作。

在此处输入图片说明

  • 这是本页所有答案的机甲。我什至会说这应该在 github 上 (2认同)