【问题标题】:Set the caret at the end of the content in Froala 2在 Froala 2 中的内容末尾设置插入符号
【发布时间】:2016-02-04 11:07:09
【问题描述】:

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

【问题讨论】:

    标签: javascript froala


    【解决方案1】:

    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 的某些版本。也许您使用的是较新版本,而我的答案不再适用?
    【解决方案2】:

    据我所知,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);
    

    另见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多