web关键词搜索高亮代码

<script type="text/javascript"> 
/* 
* 参数说明: 
* obj: 对象, 要进行高亮显示的html标签节点. 
* hlWords: 字符串, 要进行高亮的关键词词, 使用 竖杠(|)或空格分隔多个词 . 
* bgColor: 背景颜色,默认为红色. 
*/ 
function MarkHighLight(obj, hlWords, bgColor) { 
hlWords = AnalyzeHighLightWords(hlWords); 
if (obj == null || hlWords.length == 0) 
return; 
if (bgColor == null || bgColor == "") { 
bgColor = "red"; 
} 
MarkHighLightCore(obj, hlWords); 
//执行高亮标记的核心方法 
function MarkHighLightCore(obj, keyWords) { 
var re = new RegExp(keyWords, "i"); 
var style = ' style="background-color:' + bgColor + ';" ' 
for (var i = 0; i < obj.childNodes.length; i++) { 
var childObj = obj.childNodes[i]; 
if (childObj.nodeType == 3) { 
if (childObj.data.search(re) == -1) continue; 
var reResult = new RegExp("(" + keyWords + ")", "gi"); 
var objResult = document.createElement("span"); 
objResult.innerHTML = childObj.data.replace(reResult, "<span" + style + ">$1</span>"); 
if (childObj.data == objResult.childNodes[0].innerHTML) continue; 
obj.replaceChild(objResult, childObj); 
} else if (childObj.nodeType == 1) { 
MarkHighLightCore(childObj, keyWords); 
} 
} 
} 
//分析关键词 
function AnalyzeHighLightWords(hlWords) { 
if (hlWords == null) return ""; 
hlWords = hlWords.replace(/\s+/g, "|").replace(/\|+/g, "|"); 
hlWords = hlWords.replace(/(^\|*)|(\|*$)/g, ""); 
if (hlWords.length == 0) return ""; 
var wordsArr = hlWords.split("|"); 
if (wordsArr.length > 1) { 
var resultArr = BubbleSort(wordsArr); 
var result = ""; 
for (var i = 0; i < resultArr.length; i++) { 
result = result + "|" + resultArr[i]; 
} 
return result.replace(/(^\|*)|(\|*$)/g, ""); 
} else { 
return hlWords; 
} 
} 
//利用冒泡排序法把长的关键词放前面 
function BubbleSort(arr) { 
var temp, exchange; 
for (var i = 0; i < arr.length; i++) { 
exchange = false; 
for (var j = arr.length - 2; j >= i; j--) { 
if ((arr[j + 1].length) > (arr[j]).length) { 
temp = arr[j + 1]; arr[j + 1] = arr[j]; arr[j] = temp; 
exchange = true; 
} 
} 
if (!exchange) break; 
} 
return arr; 
} 
} 
//end 
window.onload = function search() { 
var obj = document.getElementById("container"); 
var keyWord = "${str}";
MarkHighLight(obj, keyWord, "Yellow"); 
} 
</script>

 

转载于:https://www.cnblogs.com/kedoudejingshen/p/3540076.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值