html 高亮关键字,HTML高亮关键字的完美解决方案

const reg = new RegExp(keyword.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'))

highlight = function (node,reg){

if (node.nodeType == 3) { //只处理文本节点

const match = node.data.match(new RegExp(reg));

if (match) {

const highlightEl = document.createElement("b");

highlightEl.dataset.highlight="y"

const wordNode = node.splitText(match.index)

wordNode.splitText(match[0].length); // 切割成前 关键词 后三个Text 节点

const wordNew = document.createTextNode(wordNode.data);

highlightEl.appendChild(wordNew);//highlight 节点构建成功

wordNode.parentNode.replaceChild(highlightEl, wordNode);// 替换该文本节点

}

} else if (node.nodeType == 1 && node.dataset.highlight!="y"

) {

for (var i = 0; i < node.childNodes.length; i++) {

highlight(node.childNodes[i], reg);

i++

}

}

}

总结

以上所述是小编给大家介绍的HTML高亮关键字的完美解决方案,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

1428d0e076c3959ab11d28a39bc84fab.png

5268f80b9b1e01f982625ef6fac83ca1.png

本条技术文章来源于互联网,如果无意侵犯您的权益请点击此处反馈版权投诉

本文系统来源:php中文网