<!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> <title>关键字高亮显示</title> </head> <body> <div class="result" id="result"> <div>博客园是面向软[123]件开发者的高品质网络div媒体和社区</div> <div>博客园一直致力于为开发者打造更优秀的网络平台</div> <div>博客园是面向软件开发者的高品质网络媒体和社区</div> </div><script> function SearchHighlight(idVal,keyword) { var l = document.getElementById(idVal); if("" == keyword) return; var temp=l.innerHTML; var htmlReg = new RegExp("\<.*?\>","i"); var arrA = new Array(); //替换HTML标签 for(var i=0;true;i++) { var m=htmlReg.exec(temp); if(m) { arrA[i]=m; } else { break; } temp=temp.replace(m,"{[("+i+")]}"); } words = unescape(keyword.replace(/\+/g,' ')).split(/\s+/); //替换关键字 for (w=0;w<words.length;w++) { var r = new RegExp("("+words[w].replace(/[(){}.+*?^$|\\\[\]]/g, "\\$&")+")","ig"); temp = temp.replace(r,"<b style='color:Red;'>$1</b>"); } //恢复HTML标签 for(var i=0;i<arrA.length;i++) { temp=temp.replace("{[("+i+")]}",arrA[i]); } l.innerHTML=temp; } SearchHighlight("result","博客园 的 div [123]"); </script> </body> </html> |