查找不存在的样式参考

时间:2020-03-05 18:57:43  来源:igfitidea点击:

有没有一种工具可以为我找到我在HTML中实际上不存在的所有CSS类?

IE。如果我的HTML中有<ul class =" topnav" />,并且topnav类在任何引用的CSS文件中都不存在。

这类似于SO#33242,它询问如何查找未使用的CSS样式。这不是重复的,因为该问题询问未使用哪些CSS类。这是相反的问题。

解决方案

回答

Firefox中的错误控制台。虽然,它会给出所有CSS错误,所以我们必须通读它。

回答

IntelliJ Idea工具也可以做到这一点。

回答

我们可以将此JavaScript放在可以为我们执行此任务的页面中:

function forItems(a, f) {
  for (var i = 0; i < a.length; i++) f(a.item(i))
}

function classExists(className) {
  var pattern = new RegExp('\.' + className + '\b'), found = false

  try {
    forItems(document.styleSheets, function(ss) {
      // decompose only screen stylesheets
      if (!ss.media.length || /\b(all|screen)\b/.test(ss.media.mediaText))
        forItems(ss.cssRules, function(r) {
          // ignore rules other than style rules
          if (r.type == CSSRule.STYLE_RULE && r.selectorText.match(pattern)) {
            found = true
            throw "found"
          }
        })
    })
  } catch(e) {}

  return found
}

回答

Firefox扩展正是我们想要的功能。

它找到所有未使用的选择器。