javascrpt 页面格式化页面

下面这个页面,格式化javaScript
  1 <html>
  2 <head>
  3 <title>JS格式化工具 </title>
  4 <meta http-equiv="content-type" content="text/html; charset=gb2312" />
  5 <style>
  6 
  7 * { padding:0px; margin:5px; font-size:13px; font-family: arial 宋体; }
  8 body { overflow:auto; border:0px none black; background-color:buttonface; }
  9 li { margin:0px 0px 0px 40px; padding:2px 4px; }
 10  
 11 
 12 .quote { color:#999; }
 13 .comments { color: #009090; }
 14 .indent { margin-left:25px; }
 15 .regexp { color:#F000F0; }
 16 
 17 #divTools { height:20px; border-bottom:1px solid #555; padding-left:15px; }
 18 #divTools a { color:navy; text-decoration:none; height:20px; line-height:20px; padding:0px 25px; }
 19 #divTools a:hover { color:white; background-color:navy; text-decoration:none; height:20px; line-height:20px; }
 20 #divJSInput { display:none; width:600px; height:450px; border:2px outset buttonface; position:absolute; background-color:buttonface; z-Index:2; }
 21 #divJSInputTitle { color:white; background-color:navy; height:20px; line-height:20px; padding:0px 10px; cursor:default; }
 22 #txtJSInput { width:598px; height:406px; overflow:auto; padding:4px 8px; background-color:white;}
 23 #divJSInputBar { height:24px; padding:0px 4px; }
 24 #divJSInputBar input { width:110px; height:22px; border:1px solid #555; line-height:20px; }
 25 #divJSOutput { background-color:white; border:1px inset buttonface; width:100%; height:500px; overflow:auto; }
 26 #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; }
 27 #divWaiting input { width:140px; height:22px; border:1px solid #555; line-height:20px; cursor:default; margin-top:4px; }
 28 </style>
 29 <script type="text/javascript">
 30 
 31 
 32 window.onload=init;
 33 
 34 //------------------
 35 
 36 // Static Variable
 37 
 38 //------------------
 39 
 40 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";
 41 
 42 
 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 
 45 
 46 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";
 47 
 48 
 49 var OPS="! $ % & * + - // / : < = > ? [ ] ^ | ~ is new sizeof typeof unchecked";
 50 
 51 var regKW=new RegExp("(\\W"+KEYWORDS.replace(/ /g,"$)|(\\W")+"$)","g");
 52 
 53 var regObj=new RegExp("(\\W"+OBJECTS.replace(/ /g,"$)|(\\W")+"$)","g");
 54 
 55 
 56 var regMP=new RegExp("(\\W"+METHODS_PROPERTIES.replace(/ /g,"$)|(\\W")+"$)","g");
 57 
 58 //var regOP=new RegExp("(\\W"+OPS.replace(/ /g,"$)|(\\W")+"$)","g");
 59 
 60 var colorKW="blue";
 61 
 62 var colorObj="red";
 63 
 64 var colorMP="#FF8000";
 65 
 66 
 67 var colorOP="#004000";
 68 
 69 //------------------
 70 
 71 // Global Variables
 72 
 73 //------------------
 74 
 75 var divJSInput, txtJSInput, divJSOutput, divWaiting, spnProcess;
 76 
 77 var glbStr, glbP, glbRe, curRe, glbTimer;
 78 
 79 function init(){
 80 
 81 
 82 // init global variables
 83 
 84 divJSInput=document.getElementById("divJSInput");
 85 
 86 txtJSInput=document.getElementById("txtJSInput");
 87 
 88 divJSOutput=document.getElementById("divJSOutput");
 89 
 90 divWaiting=document.getElementById("divWaiting");
 91 
 92 
 93 spnProcess=document.getElementById("spnProcess");
 94 
 95 // init window state
 96 
 97 maximizeWindow();
 98 
 99 divJSOutput.style.width=document.body.clientWidth-2;
100 
101 divJSOutput.style.height=document.body.clientHeight-26;
102 
103 
104 // init global events
105 
106 divJSInput.onkeydown=divJSInput_keydown;
107 
108 
109 }
110 
111 //------------------
112 
113 // event scripts
114 
115 //------------------
116 
117 function divJSInput_keydown(e){
118 
119 var e=window.event?window.event:e;
120 
121 var srcEle=e.srcElement?e.srcElement:e.target;
122 
123 
124 var sel;
125 
126 if(e.keyCode==27)hideJSInput();
127 
128 if(e.keyCode==13&&e.ctrlKey)execJSInput();
129 
130 if(e.keyCode==9&&srcEle==txtJSInput){
131 
132 document.selection.createRange().text="\t";
133 
134 return(false);
135 
136 // not support FF 
137 
138 
139 }
140 
141 
142 }
143 
144 //------------------
145 
146 // functional scripts
147 
148 //------------------
149 
150 function showJSInput(){
151 
152 with(divJSInput.style){
153 
154 display="block";
155 
156 left=(document.body.clientWidth-divJSInput.offsetWidth)/2;
157 
158 top=(document.body.clientHeight-divJSInput.offsetHeight)/2;
159 
160  
161 
162 }
163 
164 txtJSInput.focus();
165 
166 return(false);
167 
168 
169 }
170 
171 function hideJSInput(){
172 
173 divJSInput.style.display="none";
174 
175 
176 }
177 
178 function execJSInput(){
179 
180 hideJSInput();
181 
182 divJSOutput.innerHTML="";
183 
184 glbStr=txtJSInput.value.replace(/\r\n[ \t]+/gi,"\r\n").replace(/(\r\n)+/gi,"\r\n");
185 
186 
187 glbP=0;
188 
189 curRe=glbRe=document.createElement("div");
190 
191 divJSOutput.appendChild(glbRe);
192 
193 glbRe.className="codeRoot";
194 
195 showWait();
196 
197 core_analysis();
198 
199 
200 }
201 
202 function showWait(){
203 
204 document.body.style.cursor="wait";
205 
206 
207 with(divWaiting.style){
208 
209 display="block";
210 
211 left=(document.body.clientWidth-divWaiting.offsetWidth)/2;
212 
213 top=(document.body.clientHeight-divWaiting.offsetHeight)/2;
214 
215 
216 }
217 
218 spnProcess.innerHTML="0.00% ( 0 / 0 )"
219 
220 return(false);
221 
222 
223 }
224 
225 function stopExec(){
226 
227 document.body.style.cursor="";
228 
229 divWaiting.style.display="none";
230 
231 txta.value=divJSOutput.innerHTML;
232 
233 try{
234 
235 clearTimeout(glbTimer);
236 
237 
238 } catch(e){
239 
240 
241 }
242 
243 return(false);
244 
245 
246 }
247 
248 function core_analysis(){
249 
250 
251 var str=" ", c="", lastState="", seq, intNextQuote, intTemp, intCount, intWordStart;
252 
253 spnProcess.innerHTML=parseFloat(glbP/glbStr.length*100).toFixed(2)+"% ( "+glbP+" / "+glbStr.length+" )";
254 
255 for(var i=glbP;
256 
257 i<glbStr.length;
258 
259 i++){
260 
261 c=glbStr.charAt(i);
262 
263 str+=htmlEncode(c);
264 
265 switch(c){
266 
267 case "\r": case " ": case "\t":
268 
269 if(lastState=="\r\n"){
270 
271 str=" ";
272 
273 break;
274 
275 
276 }
277 
278 if(c.match(/\W/)&&glbStr.charAt(i-1).match(/\w/)){
279 
280 str=str.substring(0,str.length-htmlEncode(c).length);
281 
282 
283 str=str.replace(regKW,clKW).replace(regObj,clObj).replace(regMP,clMP)+htmlEncode(c);
284 
285 
286 }
287 
288 break;
289 
290 case "\n": case ";":
291 
292 if(lastState=="\r\n"){
293 
294 str=" ";
295 
296 break;
297 
298 
299 }
300 
301 outputLn(str);
302 
303 str=" ";
304 
305 lastState="\r\n";
306 
307 
308 if(i-glbP>200){
309 
310 glbP=i+1;
311 
312 glbTimer=setTimeout(core_analysis);
313 
314 return;
315 
316 
317 }
318 
319 break;
320 
321 case "\"":
322 
323 intNextQuote=i;
324 
325 while(intNextQuote!=-1&&intNextQuote<glbStr.length){
326 
327 intNextQuote=glbStr.indexOf("\"",intNextQuote+1);
328 
329 
330 if(intNextQuote==-1||glbStr.charAt(intNextQuote-1)!="\\")break;
331 
332 intCount=0;
333 
334 intTemp=intNextQuote;
335 
336 while(glbStr.charAt(--intTemp)=="\\")intCount++;
337 
338 if(intCount%2==0)break;
339 
340 
341 }
342 
343 if(intNextQuote==-1)break;
344 
345 
346 str+="<span class=\"quote\">"+htmlEncode(glbStr.substring(i+1,intNextQuote))+"<\/span>\"";
347 
348 i=intNextQuote;
349 
350 lastState="";
351 
352 break;
353 
354 case "\'":
355 
356 intNextQuote=i;
357 
358 while(intNextQuote!=-1&&intNextQuote<glbStr.length){
359 
360 
361 intNextQuote=glbStr.indexOf("\'",intNextQuote+1);
362 
363 if(intNextQuote==-1||glbStr.charAt(intNextQuote-1)!="\\")break;
364 
365 intCount=0;
366 
367 intTemp=intNextQuote;
368 
369 while(glbStr.charAt(--intTemp)=="\\")intCount++;
370 
371 if(intCount%2==0)break;
372 
373  
374 
375 }
376 
377 if(intNextQuote==-1)break;
378 
379 str+="<span class=\"quote\">"+htmlEncode(glbStr.substring(i+1,intNextQuote))+"<\/span>\'";
380 
381 i=intNextQuote;
382 
383 lastState="";
384 
385 break;
386 
387 case "\/":
388 
389 if(glbStr.charAt(i+1)=="\/"){
390 
391 
392 intNextQuote=i;
393 
394 intNextQuote=glbStr.indexOf("\r\n",intNextQuote+1);
395 
396 if(intNextQuote==-1)intNextQuote=glbStr.length;
397 
398 str=str.substring(0,str.length-1);
399 
400 str+="<span class=\"comments\">\/"+htmlEncode(glbStr.substring(i+1,intNextQuote))+"<\/span>";
401 
402 
403 i=intNextQuote;
404 
405 
406 } else if(glbStr.charAt(i+1)=="*"){
407 
408 intNextQuote=i;
409 
410 intNextQuote=glbStr.indexOf("*\/",intNextQuote+1);
411 
412 if(intNextQuote==-1)return;
413 
414 str=str.substring(0,str.length-1);
415 
416 str+="<span class=\"comments\">\/"+htmlEncode(glbStr.substring(i+1,intNextQuote))+"*\/<\/span>";
417 
418 
419 i=intNextQuote+1;
420 
421 
422 } else if(str.match(/[=(][ \t]*\//)){
423 
424 intNextQuote=i;
425 
426 while(intNextQuote!=-1&&intNextQuote<glbStr.length){
427 
428 intNextQuote=glbStr.indexOf("\/",intNextQuote+1);
429 
430 if(intNextQuote==-1||glbStr.charAt(intNextQuote-1)!="\\")break;
431 
432 
433 intCount=0;
434 
435 intTemp=intNextQuote;
436 
437 while(glbStr.charAt(--intTemp)=="\\")intCount++;
438 
439 if(intCount%2==0)break;
440 
441 
442 }
443 
444 if(intNextQuote==-1)break;
445 
446 str+="<span class=\"regexp\">"+htmlEncode(glbStr.substring(i+1,intNextQuote))+"<\/span>\/";
447 
448 
449 i=intNextQuote;
450 
451 lastState="";
452 
453 
454 }
455 
456 lastState="";
457 
458 break;
459 
460 case "{":
461 
462 outputLn(str);
463 
464 str=" ";
465 
466 seq=document.createElement("div");
467 
468 seq.className="indent";
469 
470 curRe.appendChild(seq);
471 
472 curRe=seq;
473 
474 lastState="\r\n";
475 
476 
477 if(i-glbP>200){
478 
479 glbP=i+1;
480 
481 glbTimer=setTimeout(core_analysis);
482 
483 return;
484 
485 
486 }
487 
488 break;
489 
490 case "}":
491 
492 outputLn(str.substring(0,str.length-1));
493 
494 str="} ";
495 
496 lastState="";
497 
498 curRe=curRe.parentNode;
499 
500 break;
501 
502 default:
503 
504 if(c.match(/\w/)&&glbStr.charAt(i-1).match(/\W/)){
505 
506 intWordStart=i;
507 
508 
509 }
510 
511 if(c.match(/\W/)&&glbStr.charAt(i-1).match(/\w/)){
512 
513 str=str.substring(0,str.length-htmlEncode(c).length);
514 
515 str=str.replace(regKW,clKW).replace(regObj,clObj).replace(regMP,clMP)+htmlEncode(c);
516 
517  
518 
519 }
520 
521 lastState="";
522 
523 break;
524 
525 
526 }
527 
528 
529 }
530 
531 if(i==glbStr.length){
532 
533 if(str!=""){
534 
535 outputLn(str);
536 
537 str=" ";
538 
539 
540 }
541 
542 stopExec();
543 
544 
545 }
546 
547 
548 }
549 
550 function outputLn(theStr){
551 
552 var seq=document.createElement("p");
553 
554 seq.innerHTML=theStr;
555 
556 
557 curRe.appendChild(seq);
558 
559 
560 }
561 
562 function clKW(str){
563 
564 return(str.charAt(0)+str.substring(1).fontcolor(colorKW));
565 
566 
567 }
568 
569 function clObj(str){
570 
571 return(str.charAt(0)+str.substring(1).fontcolor(colorObj));
572 
573 
574 }
575 
576 function clMP(str){
577 
578  return(str.charAt(0)+str.substring(1).fontcolor(colorMP));
579 
580 
581 }
582 
583 function clOP(str){
584 
585 return(str.charAt(0)+str.substring(1).fontcolor(colorOP));
586 
587 
588 }
589 
590 //------------------
591 
592 // global scripts
593 
594 //------------------
595 
596 function maximizeWindow(){
597 
598 window.moveTo(0,0);
599 
600 window.resizeTo(screen.availWidth,screen.availHeight);
601 
602 
603 }
604 
605 function htmlEncode(strS){
606 
607 return(strS.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/ /g," ").replace(/\r\n/g,"<br\/>"));
608 
609 
610 }
611 
612 </script>
613 </head>
614 <body>
615 <div id="divTools">
616 <a href="#" onclick="return(showJSInput());">点击我输入要格式化的JS</a>
617 </div>
618 <div id="divJSInput">
619 <div id="divJSInputTitle">请输入JS:-</div>
620 <textarea id="txtJSInput"></textarea>
621 <div id="divJSInputBar">
622 <input type="button" value="OK" onclick="execJSInput();" />
623 <input type="button" value="Cancel" onclick="hideJSInput();" />
624 </div>
625 </div>
626 <div id="divJSOutput"></div>
627 <textarea rows=20 cols=200 id="txta">
628 </textarea>
629 <div id="divWaiting">
630 Processing...<span id="spnProcess"></span><br>
631 <input type="button" value="Stop" onclick="stopExec();" />
632 </div>
633 </body>
634 </html>

 


posted @ 2014-02-26 23:33  今夜通宵  阅读(176)  评论(0编辑  收藏  举报