语境:
我正在使用香草 javascript 开发浏览器内的 WYSIWYG 编辑器,它主要供个人使用。但是,该document.execCommand标准已经过时,我想在我的编辑器中添加粗体和斜体。我的编辑器是一个contenteditable <div>元素,它将行分隔为 child <div>。按下该Enter键时,它会自动创建一个正在处理的新 div。这就是contenteditable.
问题:
我似乎无法弄清楚如何将光标插入符号移过它所在的元素。我想要做的是获取元素,关闭它,然后移动到一个新元素。我猜想这样做的方法是附加</div><div>到当前元素innerHTML并用 将光标移过它Selection.Modify,但这似乎不起作用。
如果它是文件的末尾,我会简单地添加标签并将光标移动到末尾,但我需要它在上下文中工作。
我的代码:
html
<div id="editor">
<div>foo</div>
<br>
<div>bar</div>
<br>
<div>foobar</div>
<!-- cursor^ ^where it should be
-->
</div>
js
//get working element if that helps
let element = window.getSelection().anchorNode.parentElement; //useful tool for debugging
//insert text works fine, but can't figure out how to insert element tags into innerHTML
function insertText(text){
let selection = window.getSelection(); //get selection
let range = selection.getRangeAt(0); //get range
range.deleteContents(); //clear gunk
let node = document.createTextNode(text); //create a node to append. Problem starts here.
range.insertNode(node); //insert the node at the cursor
for(let char of text)
selection.modify('move','left','character'); //move cursor past inserted text
}
如果您能提供帮助,我将不胜感激。