保存选择以供以后在JS中使用

Mon*_*n45 5 html javascript selection textselection getselection

我在iframe中有一个带有designMode的富文本编辑器,可以对小块文本进行语法高亮显示.我希望它更新keyup上的突出显示,但是搞乱DOM会导致帧模糊,因此每次按下一个键时,插入符号都会消失,你不能再输入了.如果解析器可以记住插入符的位置,然后重新聚焦iframe并替换插入符号,那就不会有问题.我已经阅读了getSelection()它的亲戚,但显然onkeyup删除了选择,至少在Chrome中 - getSelection()在onkeyup内调用总是产生一个空选择.有没有解决的办法?

这就是我所拥有的:

<iframe>
    <html>
        <head>
            <script>
                function parse() {
                    if(window.getSelection().type != 'None') {
                        var range = window.getSelection().getRangeAt(0);
                    }
                    var text = document.body.textContent;
                    //Parse text, output is stored in newtext
                    document.body.innerHTML = newtext;
                    document.body.focus();
                    if(range) {
                        window.getSelection().removeAllRanges();
                        window.getSelection().addRange(range);
                    }
                }
            </script>
        </head>
        <body onload="document.designMode = 'on'; document.onkeyup = parse;">
            Text entered appears here
        </body>
    </html>
</iframe>
Run Code Online (Sandbox Code Playgroud)

Kal*_*vas 0

我建议使用其他一些代码荧光笔。例如CodeMirror