我尝试使用ContentEditable元素制作markdown富文本编辑器,并希望make markdown源代码有一些样式,所以编写这个解析器:
<body>
<div class="editor-content" ContentEditable="true" onKeyUp="inputChanges"></div>
</body>
<script type="text/javascript">
let inputChanges = (event) => {
//old selection info
let selection = window.getSelection();
let oldRange = selection.anchorOffset;
let oldContainer = selection.anchorNode;
let markdown = event.target.innerTex;
let parserArray = [...];
for (const i of parserArray) {
markdown = markdown.replace(i.EXP, i.todo);
}
event.target.innerHTML = markdown;
// I tried below to make cursor back
const range = document.createRange();
range.selectNodeContents(oldContainer);
range.setStart(oldContainer, oldRange);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
</script>
键入光标时将首先进入编辑器。 我尝试修复但报告错误: 给定范围不在文档中。
在innerHTML执行之前和之后检查选择: first after
我猜它是选择焦点节点的问题。如果它将焦点转移到文本节点?
(文本节点是ContentEditable div&#39; s text <div class="editor-content" ContentEditable="true" onKeyUp="inputChanges">[here is the text node]</div>
)