Find all CSS rules that apply to an element

后端 未结 9 903
温柔的废话
温柔的废话 2020-11-22 10:26

Many tools/APIs provide ways of selecting elements of specific classes or IDs. There\'s also possible to inspect the raw stylesheets loaded by the browser.

However,

9条回答
  •  [愿得一人]
    2020-11-22 10:57

    Since this question currently doesn't have a lightweight (non-library), cross-browser compatible answer, I'll try to provide one:

    function css(el) {
        var sheets = document.styleSheets, ret = [];
        el.matches = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector 
            || el.msMatchesSelector || el.oMatchesSelector;
        for (var i in sheets) {
            var rules = sheets[i].rules || sheets[i].cssRules;
            for (var r in rules) {
                if (el.matches(rules[r].selectorText)) {
                    ret.push(rules[r].cssText);
                }
            }
        }
        return ret;
    }
    

    JSFiddle: http://jsfiddle.net/HP326/6/

    Calling css(document.getElementById('elementId')) will return an array with an element for each CSS rule that matches the passed element. If you want to find out more specific information about each rule, check out the CSSRule object documentation.

提交回复
热议问题