标签:
用js实现关键字搜索高亮显示,内附源码(点击下载)
<script> //关键字高亮显示func function InitialKeywordsShow(_keywords, obj, caseTrue) { //var reg = new RegExp(_keywords, "g");//区分大小写 var reg = new RegExp(_keywords, "gi"); //不区分大小写 if (caseTrue) { var reg = new RegExp(_keywords, "g"); } if (obj && obj.childNodes && obj.childNodes.length > 0) { for (var i = 0; i < obj.childNodes.length; i++) { if (obj.childNodes[i].nodeType == 3 && obj.childNodes[i].nodeValue && obj.childNodes[i].nodeValue.length > 0) { var txtnew = obj.childNodes[i].nodeValue.replace(reg, "<font color=‘red‘ style=‘ background:#e48b00;color:#fff;‘>" + _keywords + "</font>"); var _span = document.createElement("span"); _span.innerHTML = txtnew; obj.replaceChild(_span, obj.childNodes[i]); } else if (obj.childNodes[i].nodeType == 1) { InitialKeywordsShow(_keywords, obj.childNodes[i], caseTrue); } } } } //搜索func function SearchClick() { var fonts = document.getElementsByTagName("font"); if (fonts && fonts.length > 0) { for (var i = 0; i < fonts.length; i++) { fonts[i].style.backgroundColor = "#fff"; fonts[i].style.color = "black" } } var keyWords = document.getElementById("txtKeywords").value; var obj_content = document.getElementById("content"); if (!keyWords) { alert("请输入关键字"); return false; } var upTrue = document.getElementById("chkUp").checked; InitialKeywordsShow(keyWords, obj_content, upTrue); } </script>
--尊重他人成果,转载请注明出处,谢谢!
标签:
原文地址:http://www.cnblogs.com/twgchn/p/4961878.html