ソースを参照

fix: 修复富文本高亮异常替换问题

zhangyuhan 1 年間 前
コミット
de47abd457
1 ファイル変更12 行追加8 行削除
  1. 12 8
      packages/util/modules/format/str.js

+ 12 - 8
packages/util/modules/format/str.js

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