zl程序教程

您现在的位置是:首页 >  前端

当前栏目

javascript实现页面内关键词高亮显示代码

JavaScript代码 实现 显示 页面 关键词 高亮
2023-06-13 09:15:24 时间
复制代码代码如下:

<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-type"content="text/html;charset=utf-8"/>
<title>关键字高亮显示</title>
</head>
<body>
<divclass="result"id="textbox">
<p>百度(Nasdaq简称:BIDU)是全球最大的中文搜索引擎,2000年1月由李彦宏、徐勇两人创立于北京中关村,致力于向人们提供“简单,可依赖”的</p>
<p>信息获取方式。“百度”二字源于中国宋朝词人辛弃疾的《青玉案·元夕》词句“众里寻他千百度”,象征着百度对中文信息检索技术的执著追求。</p>
</div>
<script>
functionhighlight(idVal,keyword){
vartextbox=document.getElementById(idVal);
if(""==keyword)return;
//获取所有文字内容
vartemp=textbox.innerHTML;
console.log(temp);
varhtmlReg=newRegExp("\<.*?\>","i");
vararr=newArray();

//替换HTML标签
for(vari=0;true;i++){
//匹配html标签
vartag=htmlReg.exec(temp);
if(tag){
arr[i]=tag;
}else{
break;
}
temp=temp.replace(tag,"{[("+i+")]}");
}


//讲关键词拆分并入数组
words=decodeURIComponent(keyword.replace(/\,/g,"")).split(/\s+/);

//替换关键字
for(w=0;w<words.length;w++){
//匹配关键词,保留关键词中可以出现的特殊字符
varr=newRegExp("("+words[w].replace(/[(){}.+*?^$|\\\[\]]/g,"\\$&")+")","ig");
temp=temp.replace(r,"<bstyle="color:Red;">$1</b>");
}

//恢复HTML标签
for(vari=0;i<arr.length;i++){
temp=temp.replace("{[("+i+")]}",arr[i]);
}
textbox.innerHTML=temp;
}
highlight("textbox","百度,李彦宏");
</script>
</body>
</html>