javascript - 将 CSS 文本转换为 JavaScript 对象

标签 javascript css

我将以下文本作为 JavaScript 字符串

.mybox {
 display: block; 
 width: 20px; 
 height: 20px;
 background-color: rgb(204, 204, 204);
 }

我想转换为 JavaScript 对象

var mybox = {
 'display': 'block',
 'width': '20px',
 'height': '20px';
 'background-color': 'rgb(204, 204, 204)';
};

有什么想法或已经制作好的脚本吗?

最佳答案

2017年答案

function parseCSSText(cssText) {
    var cssTxt = cssText.replace(/\/\*(.|\s)*?\*\//g, " ").replace(/\s+/g, " ");
    var style = {}, [,ruleName,rule] = cssTxt.match(/ ?(.*?) ?{([^}]*)}/)||[,,cssTxt];
    var cssToJs = s => s.replace(/\W+\w/g, match => match.slice(-1).toUpperCase());
    var properties = rule.split(";").map(o => o.split(":").map(x => x && x.trim()));
    for (var [property, value] of properties) style[cssToJs(property)] = value;
    return {cssText, ruleName, style};
} /* updated 2017-09-28 */

描述

将以下 cssText(字符串)传递给函数:

.mybox {
     display: block; 
     width: 20px; 
     height: 20px;
     background-color: rgb(204, 204, 204);
 }

...将给出以下对象:

{   cssText: ... /* the original string including new lines, tabs and spaces */, 
    ruleName: ".mybox",
    style: {
        "": undefined,
        display: "block",
        width: "20px",
        height: "20px",
        backgroundColor: "rgb(204, 204, 204)"
     }
}

用户还可以传递一个 cssText 例如:

display: block; width: 20px; height: 20px; background-color: rgb(204, 204, 204);

特点:

  • CSSRule.cssText 一起工作和 CSSStyleDeclaration.cssText .
  • 转换 CSS 属性名称 (background-color) 到 JS 属性名称 (backgroundColor)。 它甚至可以处理非常不稳定的名字, 例如 back%gr- -ound---color: red;(转换为 backGrOundColor)。
  • 能够对现有的进行大规模修改 CSSStyleDeclarations (例如 document.body.style)使用 一个电话 Object.assign(document.body.style, parseCSSText(cssText).style).
  • 当属性名称没有值时,不会失败(条目 没有冒号)甚至反之亦然。
  • 2017-09-28 更新:处理规则名称中的新行, 折叠空格。
  • 2017-09-28 更新:处理评论 (/*...*/)。

怪癖:

  • 如果规则中的最后一个 CSS 声明以分号结尾, 返回的样式将包含一个名称为空的属性 "" 和 一个 undefined 值,反射(reflect)了后面的空字符串 分号。我认为这是正确的行为。
  • 如果属性值(字符串文字),函数将返回错误结果 包括冒号或分号或 CSS 注释,例如 div::before {content: 'test:test2;/*test3*/';}。我不知道 如何避免这种情况。
  • 目前,它转换带有前缀的属性名称 例如 -somebrowser-someproperty 错误地为 SomebrowserSomeproperty 而不是 somebrowserSomeproperty。我想要一种不会毁掉的药物 代码简洁,因此我会花时间找到一个。

实例

function parseCSSText(cssText) {
    var cssTxt = cssText.replace(/\/\*(.|\s)*?\*\//g, " ").replace(/\s+/g, " ");
    var style = {}, [,ruleName,rule] = cssTxt.match(/ ?(.*?) ?{([^}]*)}/)||[,,cssTxt];
    var cssToJs = s => s.replace(/\W+\w/g, match => match.slice(-1).toUpperCase());
    var properties = rule.split(";").map(o => o.split(":").map(x => x && x.trim()));
    for (var [property, value] of properties) style[cssToJs(property)] = value;
    return {cssText, ruleName, style};
} /* updated 2017-09-28 */

Example:
    var sty = document.getElementById("mystyle");
    var out = document.getElementById("outcome");
    var styRule = parseCSSText(sty.innerHTML);
    var outRule = parseCSSText(out.style.cssText);
    out.innerHTML = 
        "<b>⦁ CSS in #mystyle</b>: " + JSON.stringify(styRule) + "<br>" +
        "<b>⦁ CSS of #outcome</b>: " + JSON.stringify(outRule);
    console.log(styRule, outRule); /* Inspect result in the console. */
<style id="mystyle">
.mybox1, /* a comment
    and new lines 
    to step up the game */
    .mybox 
{
    display: block; 
    width: 20px; height: 20px;
    background-color: /* a comment
        and a new line */ 
        rgb(204, 204, 204);
    -somebrowser-someproperty: somevalue;
}
</style>

<div id="outcome" style="
    display: block; padding: 0.5em;
    background-color: rgb(144, 224, 224);
">...</div>

<b style="color: red;">Also inspect the browser console.</b>

关于javascript - 将 CSS 文本转换为 JavaScript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8987550/

相关文章:

css - 带有 css 的按钮上的文本对齐设计和图标

css - 如何在 CSS3 中更改 mat-checkbox 背景颜色? Angular 6

javascript - 如何设置 span background-color 以便它像在 div 中一样为整行背景着色(显示 : block; not an option)

javascript - 使用 jQuery 在隐藏输入上触发按键事件

图像 slider 中的 JavaScript 模块模式

html - 在 dd 上使用表格单元格

javascript - 谷歌表格 : Move a row of data to another sheet based on cell value

javascript - HTML5 Canvas在Chrome上速度较慢,但​​在FireFox上速度较快

jQuery 添加 css 游标类型以形成提交/链接。网站性能/速度的影响?知道 "side effects"吗?

javascript - 测试 phantomCSS 找不到 ResembleJs 容器