I'm working on a non-web platform with no HTML or CSS layer, just a pure JavaScript implementation.
I would like to load a CSS file as a text string using AJAX, parse 开发者_如何学Cthe CSS into a JS objects or JSON, and then use utility library to interpret what styles should be applied to an element in the DOM tree.
How would I do that?
I think you're looking for a "JavaScript CSS parser".
Have you looked at either of these?
http://www.glazman.org/JSCSSP/
or
http://bililite.com/blog/2009/01/16/jquery-css-parser/
The first one looks like a good fit, but if you like jQuery then maybe you'd prefer the second one.
HTH
I looked at both the links @amir75 suggested. The first looked best, but the code was far too long for what I was doing. I decided to put a lightweight script together. It doesn't use jQuery, but you can if you want to load a CSS file using .get()
etc. Take a look at the example.html and the js console output to get a look at the structure. You can choose to keep the order of the elements if you're using comments in the CSS, or otherwise it will still keep the order of the elements but not those of the comments while using a simpler JSON structure.
https://github.com/aramkocharyan/CSSJSON
Usage:
// To JSON, ignoring order of comments etc
var json = CSSJSON.toJSON(cssString);
// To JSON, keeping order of comments etc
var json = CSSJSON.toJSON(cssString, true);
// To CSS
var css = CSSJSON.toCSS(jsonObject);
Try the below code "without" any external library:
function cssToJson(cssStr){
var tmp="";
//handling the colon in psuedo-classes
var openBraces=0;
for(var i=0;i<cssStr.length;i++){
var c=cssStr[i];
if(c=="{"){openBraces++;}
else if(c=="}"){openBraces--;}
if(openBraces==0 && c==":"){
tmp+="_--_";
} else {
tmp+=c;
}
}
cssStr=tmp;
cssStr=cssStr.split("\"").join("'");
cssStr=cssStr.split(" ").join("_SPACE_");
cssStr=cssStr.split("\r").join("");
cssStr=cssStr.split("\n").join("");
cssStr=cssStr.split("\t").join("");
cssStr=cssStr.split("}").join("\"}####\"");
cssStr=cssStr.split(";\"").join("\"");
cssStr=cssStr.split(":").join("\":\"");
cssStr=cssStr.split("{").join("\":{\"");
cssStr=cssStr.split(";").join("\",\"");
cssStr=cssStr.split("####").join(",");
cssStr=cssStr.split("_--_").join(":");
cssStr=cssStr.split("_SPACE_").join(" ");
if(cssStr.endsWith(",")){
cssStr=cssStr.substr(0,cssStr.length-1);
}
if(cssStr.endsWith(",\"")){
cssStr=cssStr.substr(0,cssStr.length-2);
}
cssStr="{\""+cssStr+"}";
try{
var jsn=JSON.parse(cssStr);
return jsn;
} catch(e){
console.log(e);
return null;
}
}
精彩评论