<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <META name="Author" content="Sheneyan" /> <script type="text/javascript"> function encode(s){ return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/([\\\.\*\[\]\(\)\$\^])/g,"\\$1"); } function decode(s){ return s.replace(/\\([\\\.\*\[\]\(\)\$\^])/g,"$1").replace(/>/g,">").replace(/</g,"<").replace(/&/g,"&"); } function highlight(s){ if (s.length==0){ alert('搜索关键词未填写!'); return false; } s=encode(s); var obj=document.getElementsByTagName("body")[0]; var t=obj.innerHTML.replace(/<span\s+class=.?highlight.?>([^<>]*)<\/span>/gi,"$1"); obj.innerHTML=t; var cnt=loopSearch(s,obj); t=obj.innerHTML var r=/{searchHL}(({(?!\/searchHL})|[^{])*){\/searchHL}/g t=t.replace(r,"<span class='highlight'>$1</span>"); obj.innerHTML=t; alert("搜索到关键词"+cnt+"处") } function loopSearch(s,obj){ var cnt=0; if (obj.nodeType==3){ cnt=replace(s,obj); return cnt; } for (var i=0,c;c=obj.childNodes[i];i++){ if (!c.className||c.className!="highlight") cnt+=loopSearch(s,c); } return cnt; } function replace(s,dest){ var r=new RegExp(s,"g"); var tm=null; var t=dest.nodeValue; var cnt=0; if (tm=t.match(r)){ cnt=tm.length; t=t.replace(r,"{searchHL}"+decode(s)+"{/searchHL}") dest.nodeValue=t; } return cnt; } </script> <style type="text/css"> .highlight{background:red;font-weight:bold;color:white;} </style> </head> <body> <form onsubmit="highlight(this.s.value);return false;"> <p><input name="s" id="s" title="搜索内容:" value="中华民国" /><input type="submit" value="搜索"/></p> </form> <div id="content"> <p>1911年十月十日,国父孙中山先生和革命党同志们经历了十次革命失败, </div> </body> </html>
以上是互联网版本的页面,
?
而我主要是针对文章内容(包括从word复制到编辑器,其中有相关样式及文字格式控制内容)的搜索;
使用上页的代码我经过测试,在ie中会出现{searchHL},但本人对js RegExp不太精通,故做以下修改
var i =0; function highlight(){ ...... i=i+1; t=t.replace(r,"<span class='highlight2'>$1</span>"); t=t.replace(r,"<span class='highlight2'>$1</span>"); obj.innerHTML=t; if(i/2==1){ highlight(); } }
?
?