WEB开发网
开发学院网页设计JavaScript JavaScript 批量版JS加亮器 阅读

JavaScript 批量版JS加亮器

 2009-05-04 20:04:44 来源:WEB开发网   
核心提示:直接转为高亮版,IE+FF+Cr测试通过:代码: 程序代码<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transiti

直接转为高亮版,IE+FF+Cr测试通过:

代码:


 程序代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
         <title>PReh(al)</title>
         <style type="text/CSS">
             pre.preh{font-family:Consolas,"Lucida Console",monospace;}
             pre.preh ol{border:1px solid #ddd;margin:0;padding:0 0 0 4em;color:gray;}
             pre.preh ol li{line-height:1.75em;border-bottom:1px solid #ddd;border-left:1px solid #ddd;}
             pre.preh ol li span{color:black;white-space:pre;}
    pre.preh ol li span span.regexp{background:green;color:white}
             pre.preh ol li span em{color:blue;font-style:normal;}
    pre.preh ol li span var.object{color:red}
    pre.preh ol li span var.method_property{color:orange}
    pre.preh ol li span.comments{color:#aaa}
             pre.preh li var{color:blue;font-style:normal;}
             pre.preh li q{color:green;}
    q:before{content:none;display:none;}
         </style>
<!--[if IE]> <style>pre.preh{font-family:fixedsys,monospace}</style> <![endif]-->
<script>
//keyWords
var keywords = {js:{},html:{},css:{}};
keywords.js.keys="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";
keywords.js.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";
keywords.js.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 zIndex";
function htmlEncode(strS){
     return strS.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");
}
function htmlEncodef(c){
     return c=="&"?'&':(c=="<"?'<':(c=='>'?'>':c));
}
function htmlEncodefl(c){
     return c=="&"?5:(c=="<"||c=='>'?4:1);
}
function html2txt(strS){
     return strS.replace(/</g,"<").replace(/>/g,">").replace(/ /g," ").replace(/<br\/?>/g,"\r\n").replace(/&/g,"&").replace(/<.+?>/g,"");
}
var lexers = {}
lexers.js = {
   regKW:new RegExp("^("+keywords.js.keys.replace(/ /g,"|")+")$","g"),
   regObj:new RegExp("^("+keywords.js.objects.replace(/ /g,"|")+")$","g"),
   regMP:new RegExp("^("+keywords.js.properties.replace(/ /g,"|")+")$","g"),
   clKW:'<em>$1</em>',
   clObj:'<var class="object">$1</var>',
   clMP:'<var class="method_property">$1</var>',
   lex:function(s){
     var str=" ", c="",word='',lastState="", seq, intNextQuote, intTemp, intCount, intWordStart,glbStr=s,i;
     glbStr=glbStr.replace(/\r|\n/g,'\r\n');
     glbStr=glbStr.replace(/\r\n\r\n/g,'\r\n');
     for(i=0;i<glbStr.length;i++){
       c=glbStr.charAt(i);
       switch(c){
         case "\"":
                       str+=htmlEncodef(c);
           intNextQuote=i;
           while(intNextQuote!=-1&&intNextQuote<glbStr.length){
             intNextQuote=glbStr.indexOf("\"",intNextQuote+1);
             if(intNextQuote==-1||glbStr.charAt(intNextQuote-1)!="\\")break;
             intCount=0; intTemp=intNextQuote;
             while(glbStr.charAt(--intTemp)=="\\")intCount++;
             if(intCount%2==0)break;
           }
           if(intNextQuote==-1)break;
           str+="<q>"+htmlEncode(glbStr.substring(i+1,intNextQuote))+"<\/q>\"";
           i=intNextQuote;
           lastState="";
         break;
         case "\'":
                       str+=htmlEncodef(c);
           intNextQuote=i;
           while(intNextQuote!=-1&&intNextQuote<glbStr.length){
             intNextQuote=glbStr.indexOf("\'",intNextQuote+1);
             if(intNextQuote==-1||glbStr.charAt(intNextQuote-1)!="\\")break;
             intCount=0; intTemp=intNextQuote;
             while(glbStr.charAt(--intTemp)=="\\")intCount++;
             if(intCount%2==0)break;
           }
           if(intNextQuote==-1)break;
           str+="<q>"+htmlEncode(glbStr.substring(i+1,intNextQuote))+"<\/q>\'";
           i=intNextQuote;
           lastState="";
         break;
         case "/":
                       str+=htmlEncodef(c);
           if(glbStr.charAt(i+1)=="\/"){
             intNextQuote=i;
             intNextQuote=glbStr.indexOf('\r\n',intNextQuote+1);
             if(intNextQuote==-1)intNextQuote=glbStr.length;
             str=str.substring(0,str.length-1);
             str+="<span class=\"comments\">\/"+htmlEncode(glbStr.substring(i+1,intNextQuote))+"<\/span>";
             i=intNextQuote;
           }else if(glbStr.charAt(i+1)=="*"){
             intNextQuote=i;
             intNextQuote=glbStr.indexOf("*\/",intNextQuote+1);
             if(intNextQuote==-1)return;
             str=str.substring(0,str.length-1);
             str+="<span class=\"comments\">\/"+htmlEncode(glbStr.substring(i+1,intNextQuote))+"*\/<\/span>";
             i=intNextQuote+1;
           }else if(str.match(/(?:(?:[!=(]|<\/var>|\[|,|\n|\:)[ \t]*\/$)|^\n?[\t ]*\/$/)){
             intNextQuote=i;
             while(intNextQuote!=-1&&intNextQuote<glbStr.length){
               intNextQuote=glbStr.indexOf("\/",intNextQuote+1);
               if(intNextQuote==-1||glbStr.charAt(intNextQuote-1)!="\\")break;
               intCount=0;intTemp=intNextQuote;
               while(glbStr.charAt(--intTemp)=="\\")intCount++;
               if(intCount%2==0)break;
             }
             if(intNextQuote==-1)break;
             str+="<span class=\"regexp\">"+htmlEncode(glbStr.substring(i+1,intNextQuote))+"<\/span>\/";
             i=intNextQuote;
             lastState="";
           }
           lastState="";
         break;
         default:
                                         if(c.match(/\w/))word+=c; //in a word
           if(c.match(/\W/)){
                                                 if(word!='')
                                                     str+=word.replace(this.regKW,this.clKW).replace(this.regObj,this.clObj).replace(this.regMP,this.clMP) + htmlEncodef(c)
                                                 else str+=htmlEncodef(c);
                                                 word = '';
           }
           lastState="";
         break;
       }
     }
     return str.replace(/(\s*\r?\n)+$/,'');
   }
};
function str2styled(x,language){
   var _A = lexers[language].lex(html2txt(x)).split(/\n/);
   for(i=0;i<_A.length;i++){_A[i] = '<li><span>'+_A[i].replace(/\r/g,'').replace(/\t/g,'  ').replace(/  /g,'  ')+'</span></li>';}
   return '<ol>'+_A.join('')+'</ol>';    
}
             var $ = function(e){return document.getElementById(e)};
             window.onload = function(){
                 var pres = document.getElementsByTagName('pre');
                 for(k=0;k<pres.length;k++)if(pres[k].className.match(/\bpreh\b/))
                     pres[k].innerHTML = str2styled(pres[k].innerHTML,'js')
             }
         </script>
   </head>
   <body>
<pre id="test" class="preh js">
var point = function(){
   this.x = 1;
   this.y = 2;
   this.valueOf = function(){return 'Point:('+x+','+y+')'};
}
if(c<2)f()
var P = new point();
alert(P.valueOf());
var rex_factory = function(){return {x:/re/g,y:/rere/g,z:[/re/,/rere/,/rerere/]}};
</pre>

<pre id="test2" class="preh js">
another = 'this is another example'
</pre>

   </body>
</html>

Tags:JavaScript 批量 JS

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接