js代码格式化工具(简单格式化,显示进度条)

canRun

原文:js代码格式化工具

演示地址

View Code
  1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2 <html xmlns="http://www.w3.org/1999/xhtml">
  3 <head>
  4 <title>JSer</title>
  5 <meta http-equiv="content-type" content="text/html; charset=gb2312" />
  6 <style>
  7 /* Global CSS */
  8 * { padding:0px; margin:0px; font-size:13px; font-family: arial 宋体; }
  9 body { overflow:auto; border:0px none black; background-color:buttonface; }
 10 li { margin:0px 0px 0px 40px; padding:2px 4px; }
 11 /* Class CSS */
 12  
 13 .quote { color:#999; }
 14 .comments { color: #009090; }
 15 .indent { margin-left:25px; }
 16 .regexp { color:#F000F0; }
 17  
 18 /* Identified CSS */
 19 #divTools { height:20px; border-bottom:1px solid #555; padding-left:15px; }
 20 #divTools a { color:navy; text-decoration:none; height:20px; line-height:20px; padding:0px 25px; }
 21 #divTools a:hover { color:white; background-color:navy; text-decoration:none; height:20px; line-height:20px; }
 22 #divJSInput { display:none; width:600px; height:450px; border:2px outset buttonface; position:absolute; background-color:buttonface; z-Index:2; }
 23 #divJSInputTitle { color:white; background-color:navy; height:20px; line-height:20px; padding:0px 10px; cursor:default; }
 24 #txtJSInput { width:598px; height:406px; overflow:auto; padding:4px 8px; background-color:white;}
 25 #divJSInputBar { height:24px; padding:0px 4px; }
 26 #divJSInputBar input { width:110px; height:22px; border:1px solid #555; line-height:20px; }
 27 #divJSOutput { background-color:white; border:1px inset buttonface; width:100%; height:500px; overflow:auto; }
 28 #divWaiting { display:none; width:400px; height:60px; border:1px solid buttonface; position:absolute; background-color:#E0F0F0; z-Index:3; text-align:center; padding-top:10px; }
 29 #divWaiting input { width:140px; height:22px; border:1px solid #555; line-height:20px; cursor:default; margin-top:4px; }
 30 </style>
 31 <script type="text/javascript">
 32 /**********************
 33 Author: Hutia
 34 *********************/
 35  
 36 window.onload=init;
 37  
 38 //------------------
 39 // Static Variable
 40 //------------------
 41  
 42 var KEYWORDS="abstract break byte case catch char class const continue default delete do double else extends false final finally float for function goto if implements import in instanceof int interface long native null package private protected public reset return short static super switch synchronized this throw transient true try var void while with";
 43 var OBJECTS="Anchor Applet Area Arguments Array Boolean Button Checkbox Collection Crypto Date Dictionary Document Drive Drives Element Enumerator Event File FileObject FileSystemObject FileUpload Folder Folders Form Frame Function Global Hidden History HTMLElement Image Infinity Input JavaArray JavaClass JavaObject JavaPackage JSObject Layer Link Math MimeType Navigator Number Object Option Packages Password Plugin PrivilegeManager Random RegExp Screen Select String Submit Text Textarea URL VBArray Window WScript";
 44 var METHODS_PROPERTIES="above abs acos action activeElement alert alinkColor all altKey anchor anchors appCodeName applets apply appName appVersion arguments arity asin assign atan atan2 atob   availHeight availLeft availTop availWidth ActiveXObject back background below bgColor big blink blur bold border borderWidths bottom btoa button call callee caller cancelBubble captureEvents ceil charAt charCodeAt charset checked children classes className clear clearInterval clearTimeout click clientInformation   clientX clientY close closed colorDepth compile complete concat confirm constructir contains contextual cookie cos crypto ctrlKey current data defaultCharset defaultChecked defaultSelected defaultStatus defaultValue description disableExternalCapture disablePrivilege document domain E Echo   element elements embeds enabledPlugin enableExternalCapture enablePrivilege encoding escape eval event exec exp expando FromPoint fgColor fileName find fixed floor focus fontColor fontSize form forms forward frames fromCharCode fromElement   getAttribute get getClass getDate getDay getFullYear getHours getMember getMilliseconds getMinutes getMonth getSeconds getSelection getSlot getTime getTimezoneOffset   getUTCDate getUTCDay getUTCFullYear getUTCHours getUTCMilliseconds getUTCMinutes getUTCMonth getUTCSeconds getWindow getYear global go HandleEvent Height   hash hidden history home host hostName href hspace id ids ignoreCase images index indexOf inner innerHTML innerText innerWidth insertAdjacentHTML insertAdjacentText isFinite isNAN italics java javaEnabled join keyCode Links LN10 LN2 LOG10E LOG2E   lang language lastIndex lastIndexOf lastMatch lastModified lastParen layers layerX layerY left leftContext length link linkColor load location locationBar log lowsrc MAX_VALUE MIN_VALUE   margins match max menubar method mimeTypes min modifiers moveAbove moveBelow moveBy moveTo moveToAbsolute multiline NaN NEGATIVE_INFINITY   name navigate navigator netscape next number offscreenBuffering offset offsetHeight offsetLeft offsetParent offsetTop offsetWidth offsetX offsetY onabort onblur onchange onclick ondblclick ondragdrop onerror onfocus   onHelp onkeydown onkeypress onkeyup onload onmousedown onmousemove onmouseout onmouseover onmouseup onmove onreset onresize onsubmit onunload open opener options outerHeight   outerHTML outerText outerWidth POSITIVE_INFINITY PI   paddings pageX pageXOffset pageY pageYOffset parent parentElement parentLayer parentWindow parse parseFloat parseInt pathname personalbar pixelDepth platform plugins pop   port pow preference previous print prompt protocol prototype push random readyState reason referrer refresh releaseEvents reload removeAttribute removeMember replace resizeBy resizeTo returnValue reverse right rightcontext round SQRT1_2 SQRT2   screenX screenY scroll scrollbars scrollBy scrollIntoView scrollTo search select selected selectedIndex self setAttribute setDay setFullYear setHotkeys setHours setInterval   setMember setMilliseconds setMinutes setMonth setResizable setSeconds setSlot setTime setTimeout setUTCDate setUTCFullYear setUTCHours setUTCMillseconds setUTCMinutes   setUTCMonth setUTCSeconds setYear setZOptions shift shiftKey siblingAbove siblingBelow signText sin slice smallsort source sourceIndex splice split sqrt src   srcElement srcFilter status statusbar stop strike style sub submit substr substring suffixes sun sup systemLanguage TYPE   tagName tags taint taintEnabled tan target test text title toElement toGMTString toLocaleString toLowerCase toolbar top toString toUpperCase toUTCString type typeOf UTC unescape unshift untaint unwatch userAgent userLanguage   value valueOf visibility vlinkColor vspace watch which width window write writeln x y zIndex";
 45 var OPS="! $ % & * + - // / : < = > ? [ ] ^ | ~ is   new sizeof   typeof unchecked";
 46  
 47 var regKW=new RegExp("(\\W"+KEYWORDS.replace(/ /g,"$)|(\\W")+"$)","g");
 48 var regObj=new RegExp("(\\W"+OBJECTS.replace(/ /g,"$)|(\\W")+"$)","g");
 49 var regMP=new RegExp("(\\W"+METHODS_PROPERTIES.replace(/ /g,"$)|(\\W")+"$)","g");
 50 //var regOP=new RegExp("(\\W"+OPS.replace(/ /g,"$)|(\\W")+"$)","g");
 51  
 52 var colorKW="blue";
 53 var colorObj="red";
 54 var colorMP="#FF8000";
 55 var colorOP="#004000";
 56  
 57 //------------------
 58 // Global Variables
 59 //------------------
 60 var divJSInput, txtJSInput, divJSOutput, divWaiting, spnProcess;
 61 var glbStr, glbP, glbRe, curRe, glbTimer;
 62  
 63 function init(){
 64 // init global variables
 65 divJSInput=document.getElementById("divJSInput");
 66 txtJSInput=document.getElementById("txtJSInput");
 67 divJSOutput=document.getElementById("divJSOutput");
 68 divWaiting=document.getElementById("divWaiting");
 69 spnProcess=document.getElementById("spnProcess");
 70  
 71 // init window state
 72 maximizeWindow();
 73  
 74 divJSOutput.style.width=document.body.clientWidth-2;
 75 divJSOutput.style.height=document.body.clientHeight-26;
 76  
 77 // init global events
 78 divJSInput.onkeydown=divJSInput_keydown;
 79 }
 80  
 81  
 82 //------------------
 83 // event scripts
 84 //------------------
 85  
 86 function divJSInput_keydown(e){
 87 var e=window.event?window.event:e;
 88 var srcEle=e.srcElement?e.srcElement:e.target;
 89 var sel;
 90 if(e.keyCode==27)hideJSInput();
 91 if(e.keyCode==13&&e.ctrlKey)execJSInput();
 92 if(e.keyCode==9&&srcEle==txtJSInput){
 93    document.selection.createRange().text="\t";return(false); // not support FF
 94 }
 95 }
 96  
 97  
 98 //------------------
 99 // functional scripts
100 //------------------
101  
102 function showJSInput(){
103 with(divJSInput.style){
104    display="block";
105    left=(document.body.clientWidth-divJSInput.offsetWidth)/2;
106    top=(document.body.clientHeight-divJSInput.offsetHeight)/2;
107 }
108  
109 txtJSInput.focus();
110  
111 return(false);
112 }
113  
114 function hideJSInput(){
115 divJSInput.style.display="none";
116 }
117  
118 function execJSInput(){
119 hideJSInput();
120  
121 divJSOutput.innerHTML="";
122  
123 glbStr=txtJSInput.value.replace(/\r\n[ \t]+/gi,"\r\n").replace(/(\r\n)+/gi,"\r\n");
124 glbP=0;
125 curRe=glbRe=document.createElement("div");
126  
127 divJSOutput.appendChild(glbRe);
128  
129 glbRe.className="codeRoot";
130  
131 showWait();
132 core_analysis();
133 }
134  
135 function showWait(){
136 document.body.style.cursor="wait";
137  
138 with(divWaiting.style){
139    display="block";
140    left=(document.body.clientWidth-divWaiting.offsetWidth)/2;
141    top=(document.body.clientHeight-divWaiting.offsetHeight)/2;
142 }
143 spnProcess.innerHTML="0.00%   ( 0 / 0 )"
144 return(false);
145 }
146  
147 function stopExec(){
148 document.body.style.cursor="";
149 divWaiting.style.display="none";
150 try{clearTimeout(glbTimer);}catch(e){}
151  
152 return(false);
153 }
154  
155 function core_analysis(){
156 var str=" ", c="", lastState="", seq, intNextQuote, intTemp, intCount, intWordStart;
157 spnProcess.innerHTML=parseFloat(glbP/glbStr.length*100).toFixed(2)+"%   ( "+glbP+" / "+glbStr.length+" )";
158 for(var i=glbP;i<glbStr.length;i++){
159    c=glbStr.charAt(i);
160    str+=htmlEncode(c);
161    switch(c){
162     case "\r": case " ": case "\t":
163      if(lastState=="\r\n"){str=" ";break;}
164      if(c.match(/\W/)&&glbStr.charAt(i-1).match(/\w/)){
165       str=str.substring(0,str.length-htmlEncode(c).length);
166       str=str.replace(regKW,clKW).replace(regObj,clObj).replace(regMP,clMP)+htmlEncode(c);
167      }
168     break;
169     case "\n": case ";":
170      if(lastState=="\r\n"){str=" ";break;}
171      outputLn(str);
172      str=" ";
173      lastState="\r\n";
174      if(i-glbP>200){
175       glbP=i+1;
176       glbTimer=setTimeout(core_analysis);
177       return;
178      }
179     break;
180     case "\"":
181      intNextQuote=i;
182      while(intNextQuote!=-1&&intNextQuote<glbStr.length){
183       intNextQuote=glbStr.indexOf("\"",intNextQuote+1);
184       if(intNextQuote==-1||glbStr.charAt(intNextQuote-1)!="\\")break;
185       intCount=0; intTemp=intNextQuote;
186       while(glbStr.charAt(--intTemp)=="\\")intCount++;
187       if(intCount%2==0)break;
188      }
189      if(intNextQuote==-1)break;
190      str+="<span class=\"quote\">"+htmlEncode(glbStr.substring(i+1,intNextQuote))+"<\/span>\"";
191      i=intNextQuote;
192      lastState="";
193     break;
194     case "\'":
195      intNextQuote=i;
196      while(intNextQuote!=-1&&intNextQuote<glbStr.length){
197       intNextQuote=glbStr.indexOf("\'",intNextQuote+1);
198       if(intNextQuote==-1||glbStr.charAt(intNextQuote-1)!="\\")break;
199       intCount=0; intTemp=intNextQuote;
200       while(glbStr.charAt(--intTemp)=="\\")intCount++;
201       if(intCount%2==0)break;
202      }
203      if(intNextQuote==-1)break;
204      str+="<span class=\"quote\">"+htmlEncode(glbStr.substring(i+1,intNextQuote))+"<\/span>\'";
205      i=intNextQuote;
206      lastState="";
207     break;
208     case "\/":
209      if(glbStr.charAt(i+1)=="\/"){
210       intNextQuote=i;
211       intNextQuote=glbStr.indexOf("\r\n",intNextQuote+1);
212       if(intNextQuote==-1)intNextQuote=glbStr.length;
213       str=str.substring(0,str.length-1);
214       str+="<span class=\"comments\">\/"+htmlEncode(glbStr.substring(i+1,intNextQuote))+"<\/span>";
215       i=intNextQuote;
216      }else if(glbStr.charAt(i+1)=="*"){
217       intNextQuote=i;
218       intNextQuote=glbStr.indexOf("*\/",intNextQuote+1);
219       if(intNextQuote==-1)return;
220       str=str.substring(0,str.length-1);
221       str+="<span class=\"comments\">\/"+htmlEncode(glbStr.substring(i+1,intNextQuote))+"*\/<\/span>";
222       i=intNextQuote+1;
223      }else if(str.match(/[=(][ \t]*\//)){
224       intNextQuote=i;
225       while(intNextQuote!=-1&&intNextQuote<glbStr.length){
226        intNextQuote=glbStr.indexOf("\/",intNextQuote+1);
227        if(intNextQuote==-1||glbStr.charAt(intNextQuote-1)!="\\")break;
228        intCount=0; intTemp=intNextQuote;
229        while(glbStr.charAt(--intTemp)=="\\")intCount++;
230        if(intCount%2==0)break;
231       }
232       if(intNextQuote==-1)break;
233       str+="<span class=\"regexp\">"+htmlEncode(glbStr.substring(i+1,intNextQuote))+"<\/span>\/";
234       i=intNextQuote;
235       lastState="";
236      }
237      lastState="";
238     break;
239     case "{":
240      outputLn(str);
241      str=" ";
242      seq=document.createElement("div");
243      seq.className="indent";
244      curRe.appendChild(seq);
245      curRe=seq;
246      lastState="\r\n";
247      if(i-glbP>200){
248       glbP=i+1;
249       glbTimer=setTimeout(core_analysis);
250       return;
251      }
252     break;
253     case "}":
254      outputLn(str.substring(0,str.length-1));
255      str="} ";
256      lastState="";
257      curRe=curRe.parentNode;
258     break;
259     default:
260      if(c.match(/\w/)&&glbStr.charAt(i-1).match(/\W/)){intWordStart=i;}
261      if(c.match(/\W/)&&glbStr.charAt(i-1).match(/\w/)){
262       str=str.substring(0,str.length-htmlEncode(c).length);
263       str=str.replace(regKW,clKW).replace(regObj,clObj).replace(regMP,clMP)+htmlEncode(c);
264      }
265      lastState="";
266     break;
267    }
268 }
269  
270 if(i==glbStr.length){
271    if(str!=""){ outputLn(str); str=" "; }
272    stopExec();
273 }
274  
275 }
276  
277 function outputLn(theStr){
278 var seq=document.createElement("p");
279 seq.innerHTML=theStr;
280 curRe.appendChild(seq);
281 }
282  
283 function clKW(str){ return(str.charAt(0)+str.substring(1).fontcolor(colorKW)); }
284  
285 function clObj(str){ return(str.charAt(0)+str.substring(1).fontcolor(colorObj)); }
286  
287 function clMP(str){ return(str.charAt(0)+str.substring(1).fontcolor(colorMP)); }
288  
289 function clOP(str){ return(str.charAt(0)+str.substring(1).fontcolor(colorOP)); }
290  
291  
292 //------------------
293 // global scripts
294 //------------------
295  
296 function maximizeWindow(){
297 window.moveTo(0,0);
298 window.resizeTo(screen.availWidth,screen.availHeight);
299 }
300  
301 function htmlEncode(strS){
302 return(strS.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/ /g," ").replace(/\r\n/g,"<br\/>"));
303 }
304 </script>
305 </head>
306 <body>
307  
308 <div id="divTools">
309 <a href="#" onclick="return(showJSInput());">Input JS</a>
310 </div>
311  
312 <div id="divJSInput">
313 <div id="divJSInputTitle">Please Input the JS:</div>
314    <textarea id="txtJSInput">
315 </textarea>
316    <div id="divJSInputBar">
317    <input type="button" value="OK" onclick="execJSInput();" />
318    <input type="button" value="Cancel" onclick="hideJSInput();" />
319 </div>
320 </div>
321  
322 <div id="divJSOutput"></div>
323  
324 <div id="divWaiting">
325 Processing...<span id="spnProcess"></span><br>
326 <input type="button" value="Stop" onclick="stopExec();" />
327 </div>
328 </body>
329 </html>

 PS:纯HTML,可运行,点击左上方Tips链接可至源码运行页。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值