Find all CSS rules that apply to an element

后端 未结 9 911
温柔的废话
温柔的废话 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 11:11

    Here is my version of getMatchedCSSRules function which support @media query.

    const getMatchedCSSRules = (el) => {
      let rules = [...document.styleSheets]
      rules = rules.filter(({ href }) => !href)
      rules = rules.map((sheet) => [...(sheet.cssRules || sheet.rules || [])].map((rule) => {
        if (rule instanceof CSSStyleRule) {
          return [rule]
        } else if (rule instanceof CSSMediaRule && window.matchMedia(rule.conditionText)) {
          return [...rule.cssRules]
        }
        return []
      }))
      rules = rules.reduce((acc, rules) => acc.concat(...rules), [])
      rules = rules.filter((rule) => el.matches(rule.selectorText))
      rules = rules.map(({ style }) => style)
      return rules
    }
    

提交回复
热议问题