js 关键词高亮(根据ID/tag高亮关键字)案例介绍_javascript技巧
程序员文章站
2022-05-09 23:01:33
...
复制代码 代码如下:
二货朋友玩游戏被骗1200块,报警后被告知不够2000没办法立案。强大的二货又往那个账号寄了800块。你说那骗子是开心呢?还是开心极了呢。
改进版
复制代码 代码如下:
function highlightWord(node, word) {
// Iterate into this nodes childNodes
if (node.hasChildNodes) {
var hi_cn;
for (hi_cn = 0; hi_cn highlightWord(node.childNodes[hi_cn], word);
}
}
// And do this node itself
if (node.nodeType == 3) { // text node
tempNodeVal = node.nodeValue.toLowerCase();
tempWordVal = word.toLowerCase();
if (tempNodeVal.indexOf(tempWordVal) != -1) {
pn = node.parentNode;
if (pn.className != "highlight") {
// word has not already been highlighted!
nv = node.nodeValue;
ni = tempNodeVal.indexOf(tempWordVal);
// Create a load of replacement nodes
before = document.createTextNode(nv.substr(0, ni));
docWordVal = nv.substr(ni, word.length);
after = document.createTextNode(nv.substr(ni + word.length));
hiwordtext = document.createTextNode(docWordVal);
hiword = document.createElement("span");
hiword.className = "highlight";
hiword.appendChild(hiwordtext);
pn.insertBefore(before, node);
pn.insertBefore(hiword, node);
pn.insertBefore(after, node);
pn.removeChild(node);
}
}
}
}
//根据Tag名高亮关键字
function SearchHighlightTag(node, key) {
if (!document.createElement) return;
if (key.length === 0) return false;
var array = new Array();
array = key.split(" ");
var element = document.getElementsByTagName(node);
for (var i = 0; i for (var j = 0; j highlightWord(element[j], array[i]);
}
}
}
//根据ID高亮关键字
function SearchHighlightID(node, key) {
if (!document.createElement) return;
if (key.length === 0) return false;
var array = new Array();
array = key.split(" ");
var element = document.getElementById(node);
for (var i = 0; i for (var j = 0; j highlightWord(element, array[i]);
}
}
}