js关键字高亮
<style>
.highlight{
background:green;
font-weight:bold;
color:white;
}
</style>
<p><input id="input"/><button onclick="highlight()">搜索</button></p>
<div id="div">
<p>搜索,文章关键字高亮显示aaa</p>
<p>搜索,文章关键字高亮显示bbb</p>
<p>搜索,文章关键字高亮显示ccc</p>
<p>搜索,文章关键字高亮显示ddd</p>
<p>搜索,文章关键字高亮显示eee</p>
<p>搜索,文章关键字高亮显示fff</p>
<p>搜索,文章关键字高亮显示hhh</p>
<script>
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){
var s=document.getElementById("input").value;
console.log(s);
if (s.length==0){
alert('搜索关键词未填写!');
return false;
}
s=encode(s);
var obj=document.getElementById("div");
var t=obj.innerHTML.replace(/<span\s+class=.?highlight.?>([^<>]*)<\/span>/gi,"$1");//把匹配到的文字替换成<span>???</span>
obj.innerHTML=t;
var cnt=loopSearch(s,obj);
t=obj.innerHTML
console.log(t);
var r=/{searchHL}(({(?!\/searchHL})|[^{])*){\/searchHL}/g
t=t.replace(r,"<span class='highlight'>$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;
}
</script>
jq关键字高亮
/*JQ关键词检索高亮标出
htmlId 需要检索的HTML内容ID
htmlContent 关键字,多个以空格隔开
*/
function keywordHighlight(htmlId,htmlContent) {
console.log(090)
var content= $("#"+htmlId).html();//获取内容
if ($.trim(htmlContent)==""){
return;//关键字为空则返回
}
var htmlReg = new RegExp("\<.*?\>", "i");
var arrA = new Array();
//替换HTML标签
for (var i = 0; true; i++) {
var m = htmlReg.exec(content);
if (m) {
arrA[i] = m;
}else {
break;
}
content = content.replace(m, "{[(" + i + ")]}");
}
words = unescape(htmlContent.replace(/\+/g, ' ')).split(/\s+/);
//替换关键字
for (w = 0; w < words.length; w++) {
var r = new RegExp("(" + words[w].replace(/[(){}.+*?^$|\\\[\]]/g, "\\$&") + ")", "ig");
content = content.replace(r, "<b><span style='color:red;font-size:16px;'><u>"+words[w]+"</u></span></b>");//关键字样式
}
//恢复HTML标签
for (var i = 0; i < arrA.length; i++) {
content = content.replace("{[(" + i + ")]}", arrA[i]);
}
$("#"+htmlId).html(content);
}
jq实现更简单方法
//html是要对比的文字,searchText是搜索框获取到的内容
//如再循环中的例子:
// 搜索联想
//function seaBox(val) {
//dataBoxMore是通过接口返回内容
//for (var i = 0; i < dataBoxMore.data.length; i++) {
//liBoxMore += '<li onclick="toDrugList(\'' + dataBoxMore.data[i].namecn + '\')">' + getnewhtml(dataBoxMore.data[i].namecn,val) + '</li>'
//}
//}
function getnewhtml(html, searchText) {
var regExp = new RegExp(searchText, 'g');
var newHtml = html.replace(regExp, '<span class="highlight" >' + searchText + '</span>');
return newHtml
}