我们在使用百度或者 google 等搜索引擎进行搜索时,他们会自动给关键词加上高亮的效果,那我们站内的搜索结果关键词如何加上高亮呢,很简单,以下分享一段使用 jquery 来实现 WordPress 中搜索结果关键词高亮的效果,代码如下:
(function($){
$.fn.textSearch = function(str,options){
var defaults = {
divFlag: true,
divStr: " ",
markClass: "",
markColor: "red",
nullReport: true,
callback: function(){
return false;
}
};
var sets = $.extend({}, defaults, options || {}), clStr;
if(sets.markClass){
clStr = "'";
}else{
clStr = "style='color:"+sets.markColor+";'";
}
//对前一次高亮处理的文字还原
$("span[rel='mark']").each(function() {
var text = document.createTextNode($(this).text());
$(this).replaceWith($(text));
});
//字符串正则表达式关键字转化
$.regTrim = function(s){
var imp = /[^.|()*+-$[]?]/g;
var imp_c = {};
imp_c["^"] = "^";
imp_c["."] = ".";
imp_c[""] = "";
imp_c["|"] = "|";
imp_c["("] = "(";
imp_c[")"] = ")";
imp_c["*"] = "*";
imp_c["+"] = "+";
imp_c["-"] = "-";
imp_c["$"] = "$";
imp_c["["] = "[";
imp_c["]"] = "]";
imp_c["?"] = "?";
s = s.replace(imp,function(o){
return imp_c[o];
});
return s;
};
$(this).each(function(){
var t = $(this);
str = $.trim(str);
if(str === ""){
alert("关键字为空");
return false;
}else{
//将关键字 push 到数组之中
var arr = [];
if(sets.divFlag){
arr = str.split(sets.divStr);
}else{
arr.push(str);
}
}
var v_html = t.html();
//删除注释
v_html = v_html.replace(/<!--(?:.*)-->/g,"");
//将 HTML 代码支离为 HTML 片段和文字片段,其中文字片段用于正则替换处理,而 HTML 片段置之不理
var tags = /[^<>]+|<(/?)([A-Za-z]+)([^<>]*)>/g;
var a = v_html.match(tags), test = 0;
$.each(a, function(i, c){
if(!/<(?:.|s)*?>/.test(c)){//非标签
//开始执行替换
$.each(arr,function(index, con){
if(con === ""){return;}
var reg = new RegExp($.regTrim(con), "g");
if(reg.test(c)){
//正则替换
c = c.replace(reg,"♂"+con+"♀");
test = 1;
}
});
c = c.replace(/♂/g,"<span rel='mark' "+clStr+">").replace(/♀/g,"</span>");
a[i] = c;
}
});
//将支离数组重新组成字符串
var new_html = a.join("");
$(this).html(new_html);
if(test === 0 && sets.nullReport){
alert("没有搜索结果");
return false;
}
//执行回调函数
sets.callback();
});
};
$(".content-main").textSearch("<?php echo $keyword;?>");//添加搜索关键词
})(jQuery);
这段代码可以对搜索空格的关键词进行切分,分别高亮效果非常好。有兴趣的朋友可去拿去尝试以下。本站的搜索以及启用该功能,你可以查看本站的搜索。