Вопрос

I'm trying to save the cursor position in my NicEdit rich text editor so that after posting to the server I can restore the exact location the user was working.

Currently I am trying to accomplish this all on the client side so that I can be sure it works before attempting to save the range variables during a post.

<textarea id="editor" style="height:500px;width:500px;"></textarea>    
<input type="button" value="Save Postion" onclick="SavePosition();return false;" />
<input type="button" value="Restore Postion" onclick="RestorePosition();return false;" />

<script type="text/javascript">
    var editor;
    $(function () {
        editor = new nicEditor({ fullPanel: false });
        editor.addInstance('editor');
    });

    var range = null;
    var sel = null;
    function RestorePosition() {
        editor.nicInstances[0].selRng(range, sel);
        $('.nicEdit-main').focus();
    }
    function SavePosition() {
        range = editor.nicInstances[0].getRng();
        sel = editor.nicInstances[0].getSel();
        $('.nicEdit-main').focus(); 
    }
</script>

If a user highlights a word, clicks Save, clicks somewhere else then clicks Restore the selection will be restored.
However if the cursor is just sitting there blinking when Save is pressed, pressing Restore will move the cursor to the start.

Это было полезно?

Решение

Ok, this turned out simpler than I thought. I had to ignore the provided functions and just act directly on the content editable div. I also have to use the bookmark as I can just store the bookmark string in a hidden field.

I should also mention that this will most likely only work in IE.

    var bookmark = null;
    function RestorePosition() {
        $('.nicEdit-main').focus();
        var range = document.selection.createRange();
        range.moveToBookmark(bookmark);
        range.select();
        $('.nicEdit-main').focus();
    }
    function SavePosition() {
        $('.nicEdit-main').focus();
        bookmark = document.selection.createRange().getBookmark;
        $('.nicEdit-main').focus();
    }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top