JS获取中文拼音首字母并通过拼音首字母快速查找(4)

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,"&"); } //高亮显示“s”指定的字符,“clear”:是否清除之前高亮显示的内容 function highlight(s, clear){ if (s.length==0){ //alert('搜索关键词未填写!'); return false; } s=encode(s); var obj=document.getElementsByTagName("body")[0]; var t = ""; if (typeof clear != 'undefined' && clear){ //清除之前高亮显示的内容 t=obj.innerHTML.replace(/<span\s+class=.?highlight.?>([^<>]*)<\/span>/gi,"$1"); obj.innerHTML=t; } var cnt=loopSearch(s,obj); t=obj.innerHTML var r=https://www.jb51.net/{searchHL}(({(?!\/searchHL})|[^{])*){\/searchHL}/g t=t.replace(r,"<span>$1</span>"); obj.innerHTML=t; } 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; }

高亮样式:

<style> .highlight{background:red;font-weight:bold;color:white; font-size:24px;} </style>

HTML:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzfssf.html