如何使用JavaScript/jQuery实现插入HTML时先闭合标签再追加新标签后重开原标签
问题原因
document.execCommand 是已被标准废弃的API,它在处理HTML插入时会自动修正不符合规范的HTML片段。你传入的以</ins>闭合标签开头的内容会被浏览器判定为非法结构,直接被修正/忽略,因此无法实现拆分原有<ins>标签的效果。
解决方案
推荐使用标准的Selection和Range API实现节点拆分插入,代码如下:
// 获取当前选区 const selection = window.getSelection(); if (!selection.rangeCount) return; const range = selection.getRangeAt(0); // 定位光标所在的<ins>父元素 const currentNode = range.commonAncestorContainer; const insNode = currentNode.nodeType === Node.TEXT_NODE ? currentNode.parentElement : currentNode; if (insNode.tagName !== 'INS') return; // 从光标位置拆分文本节点 range.splitNode(currentNode); // 创建要插入的<b>节点 const bElement = document.createElement('b'); bElement.textContent = '45'; // 将<b>插入到原有<ins>元素后面 insNode.after(bElement); // 创建新的<ins>元素,包裹原标签后半部分内容 const newInsElement = document.createElement('ins'); let nextNode = bElement.nextSibling; while (nextNode) { const tempNode = nextNode.nextSibling; newInsElement.appendChild(nextNode); nextNode = tempNode; } bElement.after(newInsElement); // 可选:将光标定位到插入内容的末尾 range.collapse(newInsElement, 0); selection.removeAllRanges(); selection.addRange(range);
运行上述代码后即可得到你预期的结构:
<ins>123</ins><b>45</b><ins>678</ins>
内容的提问来源于stack exchange,提问作者Azam Alvi
相关产品推荐
相关产品推荐

