网络编程
位置:首页>> 网络编程>> JavaScript>> Javascript实现的CSS代码高亮显示

Javascript实现的CSS代码高亮显示

  发布时间:2024-07-20 10:43:08 

标签:CSS代码,高亮

相比JavaScript,CSS的语法就简单多了,主要是处理注释、字符串、CSS样式名称、CSS样式值、缩进和换行,具体详情请看代码。

<!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=gb2312" /> <title>Javascript实现CSS代码高亮显示 </title> <style type="text/css"> body{     font-size:12px;     line-height:1.8;     font-family:'Courier New', Courier, monospace; } #area{     width:320px;     height:120px; } </style> </head> <body> <textarea id="area"> body{     font-size:12px;     line-height:1.8; } #area{     width:320px;     line-height:1.5;     font-family:"Courier New", Courier, monospace; } /* ul{ margin:0; padding:0; } */ <&#47textarea> <button id="btn">This'S Testing&hellip;&hellip;</button> <div id="pre" style="color:#F0F;"></div> <script type="text/javascript"> function $(id) {     return document.getElementById(id); }; $("btn").onclick=function(){     var code=$("area").value;     //处理注释:注释替换成 _数字_     var startIdx=endIndex=-1;     var at=0;     var commentList=[];     while(true){         startIndex=code.indexOf("/*",at);         if(startIndex==-1)break;         endIndex=code.indexOf("*/",startIndex);         if(endIndex==-1)break;                  at=endIndex+2;         commentList.push(code.substring(startIndex,at));         code=code.replace(commentList[commentList.length-1],"_"+(commentList.length-1)+"_");     }          //字符串     code=code.replace(/(['"]).*\1/g,function(m){return ""+m+""});     //CSS样式值     code=code.replace(/:(.+);/g,function(m,n){return ":"+n+";"});     //CSS样式名称     code=code.replace(/[{}]/g,function(m){         if(m=="{"){             return "{";         }else{             return "}";         }     });          //注释     code=code.replace(/_(\d+)_/g,function(m,n){return ""+commentList[n]+""});     //处理\t     code=code.replace(/^(\t+)/gm,function(m){         return (new Array(m.length+1)).join("&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;");                                         });     //处理空格     code=code.replace(/^( +)/gm, function(m) {         return (new Array(m.length + 1)).join("&amp;nbsp;");     });     //处理换行     code=code.replace(/\r?\n/g,"<br>");     $("pre").innerHTML=code; } </script> </body> </html>


0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com