拆分文本节点

Split text node

本文关键字:节点 文本 拆分      更新时间:2023-09-26

我有div[contenteditable=true]。文本可以是粗体/斜体/下划线。

<div contenteditable=true>
  <b>Text</b>
</div>

我需要将文本节点拆分为2个块:。

<div contenteditable=true>
  <b>Te</b><b>xt</b>
</div>

仅适用于Chrome和Safari。

查看Text.splitText

var b = document.querySelectorAll("div[contenteditable='true'] > *")[0];
var p = b.parentNode; // the element's parent
var t = b.firstChild; // the textNode content
var newText = t.splitText(2);    // splits the node, leaving it in place
var copy = document.createElement(b.tagName);  // make another wrapper
copy.appendChild(b.lastChild);  // move second text into the copy
p.insertBefore(copy, b.nextSibling);  // put the copy into the DOM.

请参阅http://jsfiddle.net/alnitak/JbEnL/

当您指定Chrome和Safari时,我已经使用querySelectorAll来查找初始的内部DOM元素。

这里有一种方法,可以获取div中的第一个粗体标记,并将其中的文本拆分为两个粗体标记:

初始HTML:

<div id="target" contenteditable=true>
  <b>Text</b>
</div>​

代码:

var bold = document.getElementById("target").getElementsByTagName("b")[0];
var txt = bold.innerHTML;
bold.innerHTML = txt.substr(0,2);
var newBold = document.createElement("b");
newBold.innerHTML = txt.substr(2);
bold.parentNode.insertBefore(newBold, bold.nextSibling);

工作演示:http://jsfiddle.net/jfriend00/KsPrg/