|
@@ -124,6 +124,12 @@ export function replaceKeywordWithRichText (
|
|
|
|
|
|
// 格式化需要替换的富文本
|
|
|
const richString = richChar.replace(/\$1/g, keyword)
|
|
|
+ const richTextNode = document.createElement('div')
|
|
|
+ richTextNode.innerHTML = richString;
|
|
|
+
|
|
|
+ function getRichNode () {
|
|
|
+ return richTextNode.firstChild.cloneNode(true)
|
|
|
+ }
|
|
|
|
|
|
// 递归函数来遍历DOM节点并替换文本
|
|
|
function replaceText(node) {
|
|
@@ -132,16 +138,14 @@ export function replaceKeywordWithRichText (
|
|
|
const frag = document.createDocumentFragment()
|
|
|
// 将文本分割为关键词前后的文本,以及替换的富文本
|
|
|
const parts = node.textContent.split(keyword)
|
|
|
+
|
|
|
for (let i = 0; i < parts.length; i++) {
|
|
|
- if (i === 1) {
|
|
|
- // 关键词替换为富文本
|
|
|
- const richTextNode = document.createElement('div')
|
|
|
- richTextNode.innerHTML = richString;
|
|
|
- frag.appendChild(richTextNode.firstChild);
|
|
|
- } else {
|
|
|
- // 其他文本正常添加
|
|
|
- frag.appendChild(document.createTextNode(parts[i]))
|
|
|
+ // 关键词替换为富文本
|
|
|
+ if (parts.length > 1 && i !== 0) {
|
|
|
+ frag.appendChild(getRichNode());
|
|
|
}
|
|
|
+ // 其他文本正常添加
|
|
|
+ frag.appendChild(document.createTextNode(parts[i]))
|
|
|
}
|
|
|
// 替换原始文本节点
|
|
|
node.parentNode.replaceChild(frag, node)
|