Froala editor: insert into caret position when cli

2019-07-16 14:56发布

问题:

I'm using Froala v2.6.1 and I want to insert a string into the editor exactly at the last caret position when user click a divs, but the string is always inserted at the end of the editor.

Here is the thing I did:

<div class="variable" data-value="{{user_id}}">USER ID</div>

Jquery:

$('div.variable').click(function() {
    $("#template_editor").froalaEditor('html.insert', $(this).data('value'), true); 
});

Anyone know how to solve this would be great help.

回答1:

It looks like you are loosing the context of caret. I had the same problem (Even in V3) where in i had to click an external button which would open a popup and in the popup user would select a html template which had to be inserted into the last known caret postilion.

What i did was save the caret position using selection save, open popup, get the text and restore the selection and then do html.insert

1) First save the selection

// Call this before doing any kind of insert operation
editor.selection.save();

2) Restore the selection and then insert html

// Restore the selection
editor.selection.restore();
editor.html.insert(data.Body);

Hope this helps



回答2:

It looks you have an external button there. For that the editor has a built-in mechanism, highlighted in a demo. In your case it would be something like this:

$('#template_editor')
  .on('froalaEditor.initialized', function (e, editor) {
    editor.events.bindClick($('body'), 'div.variable', function (ev) {
      var that = ev.originalEvent && ev.originalEvent.originalTarget;
      editor.html.insert($(that).data('value'));
    });
  })
  .froalaEditor()


回答3:

I had the same problem. My scenario was: click inside the editor -> click on a toolbar button -> modify editor content inside a dialog -> save modified content into the editor. The editor was loosing context while working in the dialog. I fixed it by placing a marker at the beginning of work .froalaEditor('html.insert', '{MARKER}') and use the marker afterwards to know the last caret position.

Or you can use selection.save and selection.restore methods: https://www.froala.com/wysiwyg-editor/examples/selection