How to set cursor position to end of text in CKEditor?

后端 未结 8 1302
予麋鹿
予麋鹿 2020-12-01 12:34

Is there a way to set the cursor to be at the end of the contents of a CKEditor?

This developer asked too, but received no answers:

http://cksource.com/forum

8条回答
  •  不思量自难忘°
    2020-12-01 13:20

    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

提交回复
热议问题