在JavaScript / jQuery中解析CSS [英] Parsing CSS in JavaScript / jQuery

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

问题描述

我试图在JavaScript中实现CSS的解析,以便:

  a {
color:red ;
}

被解析为对象:

  {
'a'{
'color':'red'
}
}

首先,是否有JavaScript / jQuery 可以使用?



我的实现是相当基本的,所以我确信它不是万无一失的方式。例如,它适用于基本CSS,但对于类型的属性:

  background:url(data:image / png; base64,...); 

它失败,因为我使用 split(';')分隔属性:value 对。这里,; 发生在中,因此也会在此时分割。



有其他方法吗?



这是代码:

  parseCSS:function(css){
var rules = {};
css = this.removeComments(css);
var blocks = css.split('}');
blocks.pop();
var len = blocks.length;
for(var i = 0; i {
var pair = blocks [i] .split('{');
rules [$。trim(pair [0])] = this.parseCSSBlock(pair [1]);
}
return rules;
},

parseCSSBlock:function(css){
var rule = {};
var declarations = css.split(';');
declarations.pop();
var len = declarations.length;
for(var i = 0; i< len; i ++)
{
var loc = declarations [i] .indexOf(':');
var property = $ .trim(declarations [i] .substring(0,loc));
var value = $ .trim(declarations [i] .substring(loc + 1));

if(property!=&& value!=)
rule [property] = value;
}
返回规则;
},

removeComments:function(css){
return css.replace(/ \ / \ *(\r | \\\
|。)* \\ \\*\//G,);
}

谢谢!

解决方案

有一个用JavaScript写的CSS解析器,名为 JSCSSP


I'm trying to implement parsing of CSS in JavaScript so that:

a {
  color: red;
}

is parsed into the object:

{
  'a' {
    'color': 'red'
  }
}

First off, is there a JavaScript / jQuery library I can use?

My implementation is pretty basic, so I'm sure it is not fool-proof by any means. For example, it works fine for basic CSS, but for a property of the type:

background: url(data:image/png;base64, ....);

It fails because I am using split(';') to separate property:value pairs. Here, ; occurs in the value, so it splits at that point too.

Is there an alternate way to do this?

Here is the code:

parseCSS: function(css) {
    var rules = {};
    css = this.removeComments(css);
    var blocks = css.split('}');
    blocks.pop();
    var len = blocks.length;
    for (var i = 0; i < len; i++)
    {
        var pair = blocks[i].split('{');
        rules[$.trim(pair[0])] = this.parseCSSBlock(pair[1]);
    }
    return rules;
},

parseCSSBlock: function(css) { 
    var rule = {};
    var declarations = css.split(';');
    declarations.pop();
    var len = declarations.length;
    for (var i = 0; i < len; i++)
    {
        var loc = declarations[i].indexOf(':');
        var property = $.trim(declarations[i].substring(0, loc));
        var value = $.trim(declarations[i].substring(loc + 1));

        if (property != "" && value != "")
            rule[property] = value;
    }
    return rule;
},

removeComments: function(css) {
    return css.replace(/\/\*(\r|\n|.)*\*\//g,"");
}

Thanks!

解决方案

There is a CSS parser written in Javascript called JSCSSP

这篇关于在JavaScript / jQuery中解析CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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