开发者

reset cursor position in content editable after dom change

I augment text while it is written, like e.g. syntax highlighting via spans around kewords, in a contentediatable field.

I have the common problem of the cursor jumping towards the begin of the contenteditable. I tried the solution by Nico Burns on Set cursor position on contentEditable <div> it worked in the example but not for my code, possibly because I change the DOM inside the contenteditable itself.

full code at: http://pastie.org/2060277

output.addEventListener('keyup',augmentInput,false);
        output.addEventListener('keydown',saveCursorPos,false);
        output.addEventListener('mousedown',saveCursorPos,false);
        output.addEventListener('keyup',restoreCursorPos,false);

        function saveCursorPos(e){
            //var selection = window.getSelection();
            savedRange = window.getSelection().getRangeAt(0);
            console.log("save "+e.type,savedRange);
        }

        function restoreCursorPos(e){
        document.getElementById("output").focus();

            if (savedRange != null) {
                var s = window.getSelection();

                if (s.rangeCount > 0){
                    s.removeAllRanges();
                }

                s.addRange(savedRange);
                console.log("range !=0 "+e.type, savedRange);
            }

            else {
                window.getSelection().addRange(savedRange);
                console.log("range ==0 "+e.type, savedRange);
            }
        }

striking:

  • That the Range is saved like it should on mouse click (in reference to the innermost element the cursor is in, with correct offset) but not if it is saved on keydown (than in reference to the contenteditable itself, startOffset always 0, not matter where the cursor was)
  • If I prevent the cursor to be saved on keydown and just use the mouseup to save the range it is resored like if it was never saved properly or i开发者_如何学编程t changed: reference to the contenteditable itself, startOffset always 0. So I wonder if the range object is changing e.g. reflecting changes in the DOM?


Ranges do react to changes in the DOM and there are rules governing this. Whether changes affecting selected Ranges are reflected in the selection is not specified, and browser behaviour varies.

If you're making big changes to the DOM, I'd suggest using a different approach, such as the one used by the selection save/restore module in my Rangy library, which is to insert temporary invisible marker elements in the DOM at the start and end of the selection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜