更多詳細請看https://www.8umb.com/xinwendongtai/1620.html
<script>
function keyLight(id, key, bgColor){
var oDiv = document.getElementById(id),
sText = oDiv.innerHTML,
bgColor = bgColor || "red",
Colorr = Colorr || "white",
sKey = "<span style='background-color: "+bgColor+";color: "+Colorr+";'>"+key+"</span>",
num = -1,
rStr = new RegExp(key, "g"),
rHtml = new RegExp("<.*?>","ig"), //匹配html元素
aHtml = sText.match(rHtml); //存放html元素的數(shù)組
sText = sText.replace(rHtml, '{~}'); //替換html標簽
sText = sText.replace(rStr,sKey); //替換key
sText = sText.replace(/{~}/g,function(){ //恢復(fù)html標簽
num++;
return aHtml[num];
});
oDiv.innerHTML = sText;
}
var key1 = keyLight('result', '{$eyou.field.keywords}')
</script>
二、
<script>
function keyLight(id, key, bgColor){
var oDiv = document.getElementById(id),
oChilds = oDiv.childNodes,
bgColor = bgColor || "red",
Colorr = Colorr || "white",
sKey = "<span style='background-color: "+bgColor+";color: "+Colorr+";'>"+key+"</span>",
rStr = new RegExp(key, "g");
for(var i =0; i<oChilds.length-1; i++){
if(oChilds[i].nodeType == 3 && /s/.test(oChilds[i].nodeValue)){ //刪除空白的節(jié)點
oChilds[i].parentNode.removeChild(oChilds[i]);
}
oChilds[i].innerHTML = oChilds[i].innerHTML.replace(rStr,sKey); //替換key
}
}
var key1 = keyLight('result', '{$eyou.field.keywords}');
</script>