直接转为高亮版,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 ">
<cabeça>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Preh(al)</title>
<style type="texto/css">
pre.preh{font-family:Consolas,"Lucida Console",monospace;}
pre.preh ol{borda:1px sólido #ddd;margem:0;preenchimento:0 0 0 4em;cor:cinza;}
pre.preh ol li{altura da linha: 1,75em; borda inferior: 1px sólido #ddd; borda esquerda: 1px sólido #ddd;}
pre.preh ol li span{cor:preto;espaço em branco:pre;}
pre.preh ol li span span.regexp{fundo:verde;cor:branco}
pre.preh ol li span em{cor:azul;estilo de fonte:normal;}
pre.preh ol li span var.object{cor:vermelho}
pre.preh ou li span var.method_property{cor:orange}
pre.preh ol li span.comments{cor:#aaa}
pre.preh li var{cor:azul;estilo de fonte:normal;}
pre.preh li q{cor:verde;}
q:antes{conteúdo:nenhum;exibição:nenhum;}
</estilo>
<!--[if IE]> <style>pre.preh{font-family:fixedsys,monospace}</style> <![endif]-->
<roteiro>
//palavras-chave
var palavras-chave = {js:{},html:{},css:{}};
keywords.js.keys = "abstract break byte case catch char class const continue default delete do double else estende falso final finalmente float para a função goto if implementa importação em instanceof int interface longo nativo pacote nulo privado protegido público reset retornar curto estático super switch sincronizado este lance transitório true try var void while with";
keywords.js.objects="Âncora Applet Área Argumentos Matriz Botão Booleano Caixa de seleção Coleção Cripto Data Dicionário Unidade de documento Unidades Elemento Enumerador Arquivo de eventos FileObject FileSystemObject FileUpload Pasta Pastas Form Frame Função Global Hidden History HTMLElement Image Infinity Input JavaArray JavaClass JavaObject JavaPackage JSObject Layer Link Math MimeType Navigator Number Object Opção Pacotes Senha Plugin PrivilegeManager Random RegExp Screen Select String Enviar Texto Textarea URL VBArray Window WScript";
keywords.js.properties = "acima abs acos ação activeElement alerta alinkColor todas as âncoras de âncora altKey appCodeName applets aplicam appName appVersion argumentos arity asin atribuir atan atan2 atob disponibilidade Altura disponível Disponibilidade superior Disponibilidade superior Largura ActiveXObject fundo de volta abaixo bgColor grande piscar desfocar borda em negrito borda Largura inferior btoa botão chamar chamado caller cancelBubble captureEvents ceil charAt charCodeAt charset verificado classes filhos className clear clearInterval clearTimeout click clientInformation clientX clientY fechar cor fechadaDepth compile complete concat confirm constructir contém cookie contextual cos crypto ctrlKey dados atuais defaultCharset defaultPadrão verificadoPadrão selecionadoStatus defaultDescrição do valor desabilitarExternalCapture disablePrivilege document domain E Elementos de elemento de eco incorporações habilitadasPlugin enableExternalCapture enablePrivilege encoding escape eval event exec exp expando FromPoint fgColor fileName encontrar fonte de foco de piso fixoColor fontSize form form forward frames fromCharCode fromElement getAttribute getClass getDate getDay getFullYear getHours getMember getMilliseconds getMinutes getMonth getSeconds getSelection getSlot getTime getTimezoneOffset getUTCDate getUTCDay getUTCFullYear nosso getUTCMilissegundos getUTCMinutos getUTCMês getUTCSeconds getWindow getYear global go HandleEvent Height hash histórico oculto home host hostName href hspace id ids ignoreCase images index indexOf inner innerHTML innerText innerWidth insertAdjacentHTML insertAdjacentText isFinite isNAN itálico java javaEnabled join keyCode Links LN10 LN2 LOG10E LOG2E lang idioma lastIndex lastIndexOf lastMatch lastModified lastParen camadas camadaX camadaY esquerda esquerdaComprimento do contexto link linkColor local de carregamento locationBar log lowsrc MAX_VALUE MIN_VALUE margens correspondem ao máximo método da barra de menu mimeTypes min modificadores moveAbove moveBelow moveBy moveTo moveToAbsolute multilinha NaN NEGATIVE_INFINITY nome navegar navigator netscape próximo número offscreenBuffering offset offsetHeight offsetLeft offsetParent offsetTop offsetWidth offsetY onabort onblur onchange onclick ondblclick ondragdrop onerror on concentre-se emAjuda ao pressionar a tecla online protótipo push aleatório readyState motivo referenciador atualização liberaçãoEventos recarregar removerAtributo removerMember substituir redimensionarPor resizePara retornarValor reverter à direitacontexto redondo SQRT1_2 SQRT2 telaX telaY rolar barras de rolagem scrollBy scrollIntoView scrollPara pesquisar selecionar selecionado selecionadoIndex self setAttribute setDay setFullYear setHotkeys setHours setInterval setMember setMinutes setMonth setResizable setSeconds set setTime setTimeout setUTCDate setUTCFullYear setUTCHours setUTCMillseconds setUTCMinutes setUTCMês setUTCSeconds setYear setZOptions shift shiftKey siblingAcima de siblingBelow signText sin slice smallsort source sourceIndex splice split sqrt src srcElemento srcFilter status statusbar stop strike style sub submit substr substring sufixos sun sup systemIdioma TYPE tagName tags taint taintHabilitado tan target test text title toElement toGMTString toLocaleString toLowerCase barra de ferramentas top toString toUpperCase toUTCString tipo typeOf UTC unescape unshift untaint unwatch userAgent userLanguage valor valueOf visibilidade vlinkColor vspace observe qual largura da janela escreve writeln zIndex";
função htmlEncode(strS){
return strS.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");
}
função htmlEncodef(c){
return c=="&"?'&':(c=="<"?'<':(c=='>'?'>':c));
}
função htmlEncodefl(c){
retornar c=="&"?5:(c=="<"||c=='>'?4:1);
}
função html2txt(strS){
return strS.replace(/</g,"<").replace(/>/g,">").replace(/ /g," ").replace(/<br/?>/g," rn").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:função(ões){
var str=" ", c="",word='',lastState="", seq, intNextQuote, intTemp, intCount, intWordStart,glbStr=s,i;
glbStr=glbStr.replace(/r|n/g,'rn');
glbStr=glbStr.replace(/rnrn/g,'rn');
for(i=0;i<glbStr.length;i++){
c=glbStr.charAt(i);
mudar(c){
caso """:
str+=htmlEncodef(c);
intNextQuote=i;
while(intNextQuote!=-1&&intNextQuote<glbStr.length){
intNextQuote=glbStr.indexOf(""",intNextQuote+1);
if(intNextQuote==-1||glbStr.charAt(intNextQuote-1)!=" \")break ;
intCont=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=intPróximaCitação;
últimoEstado="";
quebrar;
caso "'":
str+=htmlEncodef(c);
intNextQuote=i;
while(intNextQuote!=-1&&intNextQuote<glbStr.length){
intNextQuote=glbStr.indexOf("'",intNextQuote+1);
if(intNextQuote==-1||glbStr.charAt(intNextQuote-1)!=" \")break ;
intCont=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=intPróximaCitação;
últimoEstado="";
quebrar;
caso "/":
str+=htmlEncodef(c);
if(glbStr.charAt(i+1)=="/"){
intNextQuote=i;
intNextQuote=glbStr.indexOf('rn',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=intPróximaCitação;
}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=intPróximaCitação+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=intPróximaCitação;
últimoEstado="";
}
últimoEstado="";
quebrar;
padrão:
if(c.match(/w/))palavra+=c; //em uma palavra
if(c.match(/W/)){
se(palavra!='')
str+=word.replace(this.regKW,this.clKW).replace(this.regObj,this.clObj).replace(this.regMP,this.clMP) + htmlEncodef(c)
senão str+=htmlEncodef(c);
palavra = '';
}
últimoEstado="";
quebrar;
}
}
return str.replace(/(s*r?n)+$/,'');
}
};
função str2styled(x,linguagem){
var _A = lexers[idioma].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)};
janela.onload=função(){
var pres = document.getElementsByTagName('pré');
for(k=0;k<pres.length;k++)if(pres[k].className.match(/bprehb/))
pres[k].innerHTML = str2styled(pres[k].innerHTML,'js')
}
</script>
</head>
<corpo>
<pre id="test" class="preh js">
var ponto = função(){
isto.x = 1;
isto.y = 2;
this.valueOf = function(){return 'Ponto:('+x+','+y+')'};
}
se(c<2)f()
var P = novo ponto();
alerta(P.valueOf());
var rex_factory = function(){return {x:/re/g,y:/rere/g,z:[/re/,/rere/,/rerere/]}};
</pre>
<pre id="test2" class="preh js">
outro = 'este é outro exemplo'
</pre>
</body>
</html>