CKEditor 4: How to get and set the cursor / caret

2019-07-11 06:56发布

问题:

I am looking for a way to do 2 very basic things. I just want to retrieve the position of the caret in the text. Then I want to position the caret in a specific position in the text. The purpose is to be able to programmatically modify the text.

I have found many people who were trying to do various similar things but not quite what I wanted. In fact, most solutions are looking into the HTML, finding ranges and DOM elements. Maybe that is the way to go but I haven't found a working solution.

Looking at getting the cursor position. I found the following solution from various sources (this one for example):

var selection = e.editor.getSelection();
var range = selection.getRanges()[0];
var cursor_position = range.startOffset;

But this does not respond to my problem. In the following text:

Apple

Archers

Accent

If the cursor is put successively directly after the A of each word, it returns 1 each time. What I would want is to get 1 when positioned after the 1st A, then 6 when positioned after the 2nd A, then finally 13 after the 3rd.

In other words, it is more a matter of which character position is the cursor at in the text. It should allow me to insert text after the Xth character in the text for example.

Thank you for helping

回答1:

Looking at your last comment, you might want to try implementing something like bookmarks in CKEditor but more durable. As I have explained, the original bookmarks are removed when you post data to server or simply switch to source mode and back. What is more, empty spans which I would suggest using, are removed by the editor because they have no visual representation and are considered garbage.

What you can do is using protectedSource to protect your custom bookmark spans:

var editor = CKEDITOR.replace( 'editor1', {
    language: 'en',
    protectedSource :  /<span.*class="my-break-point".*\/>/g
});

Next you would need to come up with custom code which will insert <span class="my-break-point"/> into editor HTML whenever you need it and keep track of bookmarks so that it removes previous one when next is inserted.

Of course this is just a basic example. You can have a bookmark for collapsed selection or two bookmarks for start/end of selection if selection is not collapsed.

Please try inserting bookmarks first and see what is inserted into HTML for collapsed and non-collapsed selections: - https://docs.ckeditor.com/ckeditor4/docs/#!/api/CKEDITOR.dom.range-method-createBookmark - https://docs.ckeditor.com/ckeditor4/docs/#!/api/CKEDITOR.dom.range-method-createBookmark2

Sample code:

var range = editor.getSelection().getRanges()[0];
var bm = range.createBookmark();

If anything is unclear, please let me know.