Is it possible to find CSS rules from an HTML node via JavaScript?

前端 未结 5 1280
深忆病人
深忆病人 2020-12-09 21:49

I want to get an element in the DOM and then lookup what rules in my CSS file(s) are contributing to it\'s appearance. Similar to what firebug or webkits inspector does. Is

相关标签:
5条回答
  • 2020-12-09 22:26

    Well, it's an old subject. Good for Webkit for offering a solution. As suggested, I've looked into firebug-lite and... surprise!! For every node it loops over every rule in every stylesheet checking if the selector matches our nodes or not.

    0 讨论(0)
  • 2020-12-09 22:27

    This is what you want. WebKit only. I found out about getMatchedCSSRules by looking at the chromium web inspector source.

      function getAppliedSelectors(node) {
        var selectors = [];
        var rules = node.ownerDocument.defaultView.getMatchedCSSRules(node, '');
    
        var i = rules.length;
        while (i--) {
          selectors.push(rules[i].selectorText);
        }
        return selectors;
      }
    
    0 讨论(0)
  • 2020-12-09 22:31

    A cross-browser solution I've had good success with is http://www.brothercake.com/site/resources/scripts/cssutilities/

    It is very powerful and accurate, derives a lot more information than the webkit-only function mentioned above, and it works on all styles (including those that are cross-site and that aren't active or have been overridden).

    0 讨论(0)
  • 2020-12-09 22:31

    There is a reliable way of getting it, mentioned in this blog post:

    function getStyle(oElm, strCssRule){
        var strValue = "";
        if(document.defaultView && document.defaultView.getComputedStyle){
            strValue = document.defaultView
                .getComputedStyle(oElm, "").getPropertyValue(strCssRule);
        }
        else if(oElm.currentStyle){
            strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
                return p1.toUpperCase();
            });
            strValue = oElm.currentStyle[strCssRule];
        }
        return strValue;
    }
    

    If you are using Firefox and Firebug, you can try running this code in StackOverflow, to see what you get:

    document.defaultView.getComputedStyle(document.getElementById("custom-header"),"")
    

    And with IE and Firebug Lite, you could do:

    document.getElementById("custom-header").currentStyle
    
    0 讨论(0)
  • 2020-12-09 22:37

    Is it possible? Absolutely...is it simple (especially cross-browser with IE in the mix), not so much. If you're really interested in doing this, check out the Firebug Lite CSS source here. At least the methods are decently commented showing what information each is fetching.

    ....or if you're wanting simply to inspect in a browser that doesn't have an inspector, just use Firebug Lite.

    0 讨论(0)
提交回复
热议问题