我有 div[contenteditable=true]。文本可以是粗体/斜体/下划线。
<div contenteditable=true>
<b>Text</b>
</div>
我需要将文本节点拆分为 2 个 block :。
<div contenteditable=true>
<b>Te</b><b>xt</b>
</div>
仅适用于 Chrome 和 Safari。
最佳答案
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 元素。
关于javascript - 拆分文本节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12319466/