原生JavaScript对CSS进行格式化和压缩
全是正则表达式
测试地址:http://jsfiddle.net/dtdxrk/AX5wN/embedded/result/
1 <!DOCTYPE> 2 <HTML xmlns="http://www.w3.org/1999/xhtml"> 3 <HEAD> 4 <meta charset="utf-8" /> 5 <TITLE>原生JavaScript对CSS进行格式化和压缩</TITLE> 6 <style type="text/css"> 7 *{margin: 0;padding: } 8 body{font-family: '微软雅黑';} 9 h1{font-weight: normal;font-size: 30px;border-bottom: 1px solid #ccc;margin-bottom: 20px;background: green;color: #fff;padding: 10px;} 10 input{padding: 5px 20px;} 11 </style> 12 <BODY> 13 <h1>原生JavaScript对CSS进行格式化和压缩</h1> 14 <input type="submit" value="+格式化" id="format" /> 15 <input type="submit" value="-压缩化" id="compress" /> 16 <textarea name="" rows="" cols="" style="width:100%;height:500px;" id="code"> 17 input,button{ 18 height:20px;background-color: #ffffff;/*border:1px solid #333333;*/ 19 } 20 </textarea> 21 22 <script> 23 (function(){ 24 var $ = function(id){return document.getElementById(id)}; 25 26 $("format").onclick = function(){ 27 $("code").value = cssFormat($("code").value); 28 }; 29 30 $("compress").onclick = function(){ 31 $("code").value = cssCompress($("code").value); 32 }; 33 34 function cssFormat(code){ 35 code = code.replace(/\n/ig,''); 36 code = code.replace(/(\s){2,}/ig,'$1'); 37 code = code.replace(/\t/ig,''); 38 code = code.replace(/\n\}/ig,'\}'); 39 code = code.replace(/\n\{\s*/ig,'\{'); 40 code = code.replace(/(\S)\s*\}/ig,'$1\}'); 41 code = code.replace(/(\S)\s*\{/ig,'$1\{'); 42 code = code.replace(/\{\s*(\S)/ig,'\{$1'); 43 return code; 44 } 45 46 function cssCompress(code){ 47 code = code.replace(/(\s){2,}/ig,'$1'); 48 // code = code.replace(/(\S)\s*\{/ig,'$1\n{'); //{的换行 49 code = code.replace(/\*\/(.[^\}\{]*)}/ig,'\*\/\n$1}'); 50 code = code.replace(/\/\*/ig,'\n\/\*'); 51 code = code.replace(/;\s*(\S)/ig,';\n\t$1'); 52 code = code.replace(/\}\s*(\S)/ig,'\}\n$1'); 53 code = code.replace(/\n\s*\}/ig,'\n\}'); 54 code = code.replace(/\{\s*(\S)/ig,'\{\n\t$1'); 55 code = code.replace(/(\S)\s*\*\//ig,'$1\*\/'); 56 code = code.replace(/\*\/\s*([^\}\{]\S)/ig,'\*\/\n\t$1'); 57 code = code.replace(/(\S)\}/ig,'$1\n\}'); 58 code = code.replace(/(\n){2,}/ig,'\n'); 59 return code; 60 } 61 62 }()); 63 64 </script> 65 66 </BODY> 67 </HTML>