說明
最近博客添加了搜索功能,有個需求是要針對搜索結果中搜索關鍵字需要高亮顯示。
以便用戶可以更快速的挑選自己中意的文章。
原理就是在渲染列表數據中給含有關鍵字的文本標籤添加自定義class,渲染完畢後調用寫好的高亮js方法。
實現效果
代碼
// 搜索關鍵字高亮
var highlightKeyword=function(keyword) {
//1.獲取要高亮顯示的行
var rowNode = $('.highlightRow');
//2.獲取搜索的內容
//3.遍歷整行內容,添加高亮顏色
rowNode.each(function() {
var newHtml = $(this).html();
newHtml = newHtml.replace(keyword, '<span style="color:#ff6700;">' + keyword + '</span>');
$(this).html(newHtml);
});
}
// 拼接列表
var dataRow = "";
if (data.rows != null && data.rows != '') {
$.each(data.rows, function(i, r) {
// 拼接DOM
dataRow+='<div class="search-post-item">'+
'<h4 class="">'+
'<a href="'+ctx+'/author/'+postAuthor+'/post/detail/'+r.id+'" target="_blank">'+
'<span class="post-title highlightRow">'+r.postTitle+'</span>'+
'</a>'+
'</h4>'+
'<p class="post-content highlightRow">'+r.postExcerpt+
'</p>'+
'<div class="post-info-box">'+
'<p>' +
'<span class="date">'+new Date(r.postTime).Format("yyyy-MM-dd hh:mm:ss")+'</span>'+
'</p>'+
'<p class="point"></p>'+
'<p>'+
'<span class="read-num">閱讀數 <span class="num">'+r.readCount+'</span> </span>'+
'</p>'+
'<p class="point"></p>'+
'<p>'+
'<span class="comment-num">評論數 <span class="num">'+r.commentCount+'</span> </span>'+
'</p>'+
'</div>'
'</div>';
dataRow+='</div>';
});
// console.log(dataRow);
$("#post-list").append(dataRow);
// 高亮關鍵字
highlightKeyword(postTitle);