最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Set the caret at the end of the content in Froala 2 - Stack Overflow

programmeradmin3浏览0评论

I'm using Froala 2 and the documentation doesn't seem to have anything that implies a simple way to set the location of the caret, let alone at the beginning or end. I'm trying to seed the editor instance with a little content in certain cases and when I do using html.set, the caret just stays where it is at the beginning and I want to move it to the end. The internet doesn't seem to have anything helpful around this for v2.

I'm using Froala 2 and the documentation doesn't seem to have anything that implies a simple way to set the location of the caret, let alone at the beginning or end. I'm trying to seed the editor instance with a little content in certain cases and when I do using html.set, the caret just stays where it is at the beginning and I want to move it to the end. The internet doesn't seem to have anything helpful around this for v2.

Share Improve this question edited Dec 12, 2015 at 22:53 C. Augusto Proiete 28k3 gold badges78 silver badges100 bronze badges asked Dec 12, 2015 at 22:10 webbowerwebbower 7861 gold badge7 silver badges21 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

Froala support provided an answer for me that works:

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

As far as I know, Froala 2 doesn't provide any API to do this, but you can use native JavaScript Selection API.

This code should do the job:

// 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);

See also:

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

评论列表(0)

  1. 暂无评论