从外部类中获取CSS

时间:2012-07-20 14:47:42

标签: javascript jquery css

修改 用regexpr添加了一个测试来解决techfoobar指出的问题

编辑2 为其他人更正的代码hf:)

我正在寻找一种从指定类中获取所有静态样式的方法。我不想附加一个新div并从中提取所有可能的值,因为值通常只是计算...

以下是一些相关帖子:

jQuery CSS plugin that returns computed style of element to pseudo clone that element?

Can jQuery get all CSS styles associated with an element?

http://quirksmode.org/dom/w3c_css.html

这是我到目前为止所得到的:

function getExternalCSS(className) {
    var cssText = false;
    $.each(document.styleSheets, function(key, value) {
        $.each(value.cssRules, function(k, v) {
            if(new RegExp(className, "i").test(v.selectorText)) {
                cssText = v.cssText;
                return false;
            }
        });
        if(cssText !== false) {
            return false;
        }
    });
    return cssText;
}

css浏览:

.someClass {
    style1...
}
.someOtherClass {
    style2...
}
.myClassToFind {
    style3...
}

用法:

    getExternalCSS(".myClassToFind");  //note the . for class

正确返回了selectorText,但永远不会触发if。我已经尝试解析字符串等任何想法?

1 个答案:

答案 0 :(得分:1)

<强>更新

查看此演示:http://jsfiddle.net/XaB3T/1/

有几个问题:

a)您需要return false $.each来停止循环,就像break一样。这没有做到。 b)您正在检查v.selectorText.toLowerCase() '.myClass''.myClass'肯定无法匹配,因为For counting in only those styles that will be applied at the end, you might need to do a lot more!并非全部小案例


if

解释

有关CSS特异性规则,请参阅:


.yourClass永远不会返回true,因为:

a)选择器文本不必完全是.a .yourClass。它可以是div.yourClass.anotherClass, .yourClass甚至for each selectorText { strip off any { character split the selector text by ',' into an array called parts for each part { check if it ends with '.yourClass' // if it does, this class is match } } 等等。所有这些都指向您的元素

b)支票需要是:

{{1}}

另一个问题是CSS特异性。要仅计算将在最后应用的那些样式,您可能需要做更多的事情!

相关问题