【发布时间】:2016-02-04 11:07:09
【问题描述】:
我正在使用 Froala 2,文档似乎没有任何暗示设置插入符号位置的简单方法,更不用说在开头或结尾了。在某些情况下,我试图用一些内容为编辑器实例播种,当我使用html.set 时,插入符号只是停留在开头的位置,我想将它移到结尾。对于 v2,互联网似乎对此没有任何帮助。
【问题讨论】:
标签: javascript froala
我正在使用 Froala 2,文档似乎没有任何暗示设置插入符号位置的简单方法,更不用说在开头或结尾了。在某些情况下,我试图用一些内容为编辑器实例播种,当我使用html.set 时,插入符号只是停留在开头的位置,我想将它移到结尾。对于 v2,互联网似乎对此没有任何帮助。
【问题讨论】:
标签: javascript froala
Froala 支持为我提供了一个可行的答案:
var editor = $('#edit').data('froala.editor');
editor.selection.setAtEnd(editor.$el.get(0));
editor.selection.restore();
【讨论】:
editor.events.focus() 之前强制关注编辑器。
editor.$el.get(0) 在这种情况下并不总是按预期工作。对我来说更好的是editor.selection.endElement()。
据我所知,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);
另见:
【讨论】: