开发者

Set caret to end after focus CKEditor [duplicate]

开发者 https://www.devze.com 2023-04-11 09:08 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: CKEditor - Set cursor position to end of text
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

CKEditor - Set cursor position to end of text

I have a <div> with a lot of content. After a click on this div, the CKEditor is loaded to edit this div.

Now I would like to set the caret/cursor to the end of the contents after replacing it with the editor.

My code currently is something like this:

var editor = CKEDITOR.replace('content', {
  // Setti开发者_运维技巧ngs

  // Event listeners
  on: {
    instanceReady: function(evt) {
      var editor = evt.editor;
    
      // give focus (displays caret at the beginning of the content, not the end)
      editor.focus();
    }
  }
});


After a bit of fiddling, I've got it to work with the following code:

$(document).ready(function() {

    CKEDITOR.on('instanceReady', function(ev) {

        ev.editor.focus();

        var s = ev.editor.getSelection(); // getting selection
        var selected_ranges = s.getRanges(); // getting ranges
        var node = selected_ranges[0].startContainer; // selecting the starting node
        var parents = node.getParents(true);

        node = parents[parents.length - 2].getFirst();

        while (true) {
            var x = node.getNext();
            if (x == null) {
                break;
            }
            node = x;
        }

        s.selectElement(node);
        selected_ranges = s.getRanges();
        selected_ranges[0].collapse(false);  //  false collapses the range to the end of the selected node, true before the node.
        s.selectRanges(selected_ranges);  // putting the current selection there
    }

});

The idea is:

  1. Get the root node (not body)
  2. Advance to next node, until there are no more nodes to advance to.
  3. Select last node.
  4. Collapse it
  5. Set range
0

精彩评论

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

关注公众号