将CSS文本转换为JavaScript对象 [英] Convert CSS text to JavaScript object

查看:98
本文介绍了将CSS文本转换为JavaScript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following text as a JavaScript string

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

我想转换为JavaScript对象

I want to convert to a JavaScript Object

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

任何想法或已经制作的脚本?

Any ideas or already made scripts?

推荐答案

这是一个解析器的开头,可以做你想要的。当然,它需要工作,特别是如果你想处理任何可能提供的通用css。这假设输入css是按照您提供的方式编写的,第一行是属性的名称,最后一行是}等。

This is the beginning of a parser that may do what you want. Of course it needs work, especially if you want to handle any generic css that may be provided. This assumes that input css is written as you provided, with the first row being the name of the property, the last row being a '}' and so on.

如果你不想仅处理基本属性,编写复杂的解析器不是一件容易的任务。例如,如果你声明如下:

If you don't want to handle only basic properties, writing a complex parser is not an easy task. For example, what if you declare something like:

input[type="text"],
table > tr:nth-child(2),
#link a:hover {
    -webkit-transition: width 2s; /* Safari and Chrome */
}

这是有效的css,从中提取有效的javascript变量名称?如何将 -webkit-transition 转换为有意义的属性名称?整个任务闻起来像你做错了所有错误

This is valid css, but how would you extract a valid javascript variable name from it? How to convert -webkit-transition into a meaningful property name? The whole task smells like you're doing it all wrong. Instead of working on a parser, I'd work on a more stable solution at all.

顺便说一下,这里是你可以从下面开始的代码:

By the way, here is the code you may start from:

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

    // split css by line
    var css_rows = s.split('\n'); 

    // filter out empty elements and strip ';'      
    css_rows = css_rows.filter(function(x){ return x != '' }).map(function(x){ return x.trim().replace(';', '') });

    // create object
    var json_name = css_rows[0].trim().replace(/[\.\{\ \#]/g, '');
    eval('var ' + json_name + ' = {};');
    // remove first and last element
    css_rows = css_rows.splice(1, css_rows.length-2)

    for (elem in css_rows)
    {
        var elem_parts = css_rows[elem].split(':');
        var property_name = elem_parts[0].trim().replace('-', '');
        var property_value = elem_parts[1].trim();
        eval(json_name + '.' + property_name + ' = "' + property_value + '";');
    }

这篇关于将CSS文本转换为JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆