js 关键词高亮(根据ID/tag高亮关键字)案例介绍

关键词高亮在开发中会带来很多的方便,关键词高亮包括:根据ID高亮关键字/根据Tag名高亮关键字等等,感兴趣的朋友可以了解下,希望本文对你有所帮助

复制代码 代码如下:





JS 关键词高亮










二货朋友玩游戏被骗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]);
}
}
}

以上就是js 关键词高亮(根据ID/tag高亮关键字)案例介绍的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » JavaScript 教程