1.要實(shí)現(xiàn)的效果
關(guān)鍵詞搜索時(shí)內(nèi)容結(jié)果高亮顯示
2.js文件
/**
* Created by dell on 2018/2/28.
*/
(function ($) {
$.fn.GL = function (options) {
var dataop = {
ocolor:'red',
oshuru:'高亮',
};
var chuancan = $.extend(dataop,options);
$(this).each(function()
{
var _this = $(this)
_this.find($(".glnow")).each(function()
{
$(this).css({color:""});
});
});
if(chuancan.oshuru==''){
return false;
}else{
var regExp = new RegExp("(" + chuancan.oshuru.replace(/[(){}.+*?^$|\\\[\]]/g, "\\$&") + ")", "ig");
$(this).each(function()
{
var _this1 = $(this)
var html = _this1.html();
var newHtml = html.replace(regExp, '<span class="glnow" style="color:'+chuancan.ocolor+'">'+chuancan.oshuru+'</span>');
_this1.html(newHtml);
});
}
}
})(jQuery);
將上面代碼保存到j(luò)s文件嗽冒,然后再前端引入
3.使用方式
// 文字高亮
function textHighlight() {
var text=$("#high-light-text").val();
if (text.length > 0) {
$('.content').GL({
ocolor: 'red',//設(shè)置關(guān)鍵詞高亮顏色
oshuru: text//設(shè)置要顯示的關(guān)鍵詞
});
}
}
4.效果
image.png