Răsfoiți Sursa

Merge branch 'main' into feature/v1.0.36

lianbingjie 1 an în urmă
părinte
comite
7f078ba320
1 a modificat fișierele cu 12 adăugiri și 8 ștergeri
  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 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)