http://www.ibm.com/developerworks/cn/web/wa-lo-firefox-ext/index.html
<html>
<head>
<style>
textarea{
width:800px;
height:250px;
}
</style>
<script>
function trans(){
var content = document.getElementById("content");
//去除注释
content = removeComment(content.value);
//去除换行
content = removeLine(content);
content = removeSpace(content);
//转换成css数组
var cssList = cssConvert(content);
for(var i=0;i<cssList.length;i++){
alert(cssList[i].attrName + " " +cssList[i].attrValue+ " " +cssList[i].cssNum);
}
document.getElementById("result").value = content;
}
//转换成css数组
function cssConvert(txt){
var cssList = [];
var isOpen = false;
var attrName="";
var attrValue = "";
var cssNum = 1;
for(var i=0;i<txt.length;i++){
if(txt[i] == '{') {
isOpen = true;
continue;
}
if(txt[i] == '}') {
isOpen = false;
cssList.push({attrName:attrName,attrValue:attrValue,cssNum:cssNum});
cssNum ++;
attrValue = "";
attrValue = "";
continue;
}
if(isOpen){
attrValue += txt[i];
} else {
attrName += txt[i];
}
}
return cssList;
}
//去除换行
function removeLine(txt){
txt = txt.replace(/<\/?.+?>/g,"");
txt = txt.replace(/[\r\n]/g, "");
return txt;
}
function removeSpace(txt){
var isOpen =false;
for(var i=0;i<txt.length;i++){
if(txt[i]=='{'){
isOpen = true;
if(i-1>=0&&txt[i-1] == ' ') {
txt = removeAt(txt,i-1);
i--;
}
}
if(txt[i]=='}') isOpen = false;
//符合条件的去空格
if((i-1>=0&&i+1<txt.length&&txt[i]==' '&&isOpen ==true&&(txt[i-1]==':'||txt[i+1]==':'||txt[i-1]==' '||txt[i+1]==' '||txt[i-1]==';'||txt[i+1]==';'||txt[i-1]=='{'||txt[i-1]=='}'))||(i-1>=0&&txt[i]==' '&&txt[i-1]==' ')||(i-1>=0&&txt[i]==' '&&txt[i-1]=='}')){
txt = removeAt(txt,i);
i--;
} else if(i-1>=0&&i+1<txt.length&&isOpen ==false&&txt[i]==' '&&(txt[i-1]==','||txt[i+1]==','||txt[i-1]==' '||txt[i+1]==' ') ){
txt = removeAt(txt,i);
i--;
}
}
return txt;
//return txt.replace(/\s+/g, "");//.replace(/\s+/g, "");
}
function removeAt(txt,i){
temp = txt.substr(0,i);
temp += txt.substring(i+1);
return temp;
}
//去除注释
function removeComment(txt){
while(true){
var start = txt.indexOf("/*");
var end = txt.indexOf("*/");
var temp = "";
if(start >= 0 && end >= 0){
temp = txt.substring(0,start);
temp += txt.substring(end+2);
txt = temp;
} else {
return txt;
}
}
}
</script>
</head>
<body>
<textarea id="content"></textarea>
<input type="button" value="转换" onclick="trans()"/>
<textarea id="result"></textarea>
</body>
</html>