我有div [contenteditable = true]。文字可以是粗体/斜体/下划线。
<div contenteditable=true>
<b>Text</b>
</div>
我需要将文本节点拆分为2个块:。
<div contenteditable=true>
<b>Te</b><b>xt</b>
</div>
仅适用于Chrome和Safari。
答案 0 :(得分:3)
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元素。
答案 1 :(得分:0)
这是一种获取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/