在 Froala 2 的内容末尾设置插入符

Set the caret at the end of the content in Froala 2

我使用的是 Froala 2,文档似乎没有任何暗示设置插入符位置的简单方法的内容,更不用说在开头或结尾了。在某些情况下,我试图为编辑器实例添加一些内容,当我使用 html.set 时,插入符号只是停留在它开始的位置,我想将它移到最后。互联网似乎对 v2 没有任何帮助。

据我所知,Froala 2 不提供任何 API 来执行此操作,但您可以使用原生 JavaScript Selection API.

这段代码应该可以完成工作:

// Selects the contenteditable element. You may have to change the selector.
var element = document.querySelector("#froala-editor .fr-element");
// Selects the last and the deepest child of the element.
while (element.lastChild) {
  element = element.lastChild;
}

// Gets length of the element's content.
var textLength = element.textContent.length;

var range = document.createRange();
var selection = window.getSelection();

// Sets selection position to the end of the element.
range.setStart(element, textLength);
range.setEnd(element, textLength);
// Removes other selection ranges.
selection.removeAllRanges();
// Adds the range to the selection.
selection.addRange(range);

另请参阅:

  • How to set caret(cursor) position in contenteditable element (div)?
  • Set caret position at a specific position in contenteditable div

Froala 支持人员为我提供了有效的答案:

var editor = $('#edit').data('froala.editor');
editor.selection.setAtEnd(editor.$el.get(0));
editor.selection.restore();