【问题标题】:Is there a tool matching class name to styles automatically?是否有自动将类名与样式匹配的工具?
【发布时间】:2016-12-25 17:58:54
【问题描述】:

是否有工具自动将类名与样式匹配?

如果给定一个 HTML 文件和 CSS 文件

例子:

HTML 文件

<div class="a"></div>

CSS 文件

.a {
  font-size: 12px;
  color: blue;
}

生成方式:

{
  a: {
    'font-size': '12px',
    'color': 'blue',
  }
}

【问题讨论】:

  • 你能解释一下你想要什么吗?
  • 什么?如果你想用 JS 检索样式表,请参阅StyleSheet Interface
  • 为什么要这样做?你打算如何处理结果?
  • 我正在构建一个工具。我需要一个工具作为我的依赖项。只是想知道是否有一个 npm 模块可以提供帮助:var html2css = require('html2css'); var result = html2css('main.html', 'main.css');
  • results 将是上面的对象{ a: { 'font-size': '12px', 'color': 'blue', } }

标签: javascript css


【解决方案1】:

DIY 是一种选择:

appendCss({
  "my-class": {
    "background": "yellow",
    "padding": "10px"
  }
});

function appendCss (css) {
  var style = document.createElement("style");
  style.textContent = cssToString(css);
  document.head.appendChild(style);
}

function cssToString (css) {
  var c, p, s = "";
  for (c in css) {
    s += "." + c + "{";
    for (p in css[c]) {
      s += p + ":" + css[c][p] + ";";
    }
    s += "}";
  }
  return s;
}
&lt;span class="my-class"&gt;merry xmas&lt;/span&gt;

【讨论】:

  • 鉴于您已经提供了答案,您能否编辑问题以尝试解释 OP 的意思?
  • 感谢您的回复,抱歉回复晚了。我在我的问题中添加了 cmets。你可以看看。感谢您抽出宝贵时间。
猜你喜欢
  • 2021-04-04
  • 1970-01-01
  • 1970-01-01
  • 2021-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-28
  • 1970-01-01
相关资源
最近更新 更多