How to get cursor position or location from RichTextArea in GWT?

点点圈 提交于 2019-11-29 02:23:35
Andrei Volgin

If you you want to insert something in the RichTextArea at the cursor position, you can do it with the formatter:

RichTextArea.Formatter formatter = richText.getFormatter();
formatter.insertHTML("My text is inserted at the cursor position");

To find a cursor position using JavaScript, try the solution proposed by Tim Down:

Get a range's start and end offset's relative to its parent container

In Vaadin 7.5 @AndreiVolgin answer seems not working. But if somebody wants only to paste some text in cursor position, then CKEditor wrapper for Vaadin add-on may help (link).

Here is an example for posterity:

CKEditorTextField textArea;
// and for example in some listener function we could call:
textArea.insertHtml("<b>some html</b>");
textArea.insertText("sample text");
Tim Hill

Don't know if this is still required, but I have been trying to do exactly the same today and could not really find a definitive answer. I did find this non-GWT solution (Get caret (cursor) position in contentEditable area containing HTML content), which needed tweaking everso slightly. Hope this helps someone.

    public static native int getCursor(Element elem) /*-{
    var node = elem.contentWindow.document.body
    var range = elem.contentWindow.getSelection().getRangeAt(0);

    var treeWalker = $doc.createTreeWalker(node, NodeFilter.SHOW_TEXT, function(node) {
        var nodeRange = $doc.createRange();
        nodeRange.selectNodeContents(node);
        return nodeRange.compareBoundaryPoints(Range.END_TO_END, range) < 1 ? NodeFilter.FILTER_ACCEPT
                : NodeFilter.FILTER_REJECT;
    }, false);

    var charCount = 0;
    while (treeWalker.nextNode()) {
        charCount += treeWalker.currentNode.length;
    }

    if (range.startContainer.nodeType == 3) {
        charCount += range.startOffset;
    }

    return charCount;
}-*/;

Try this out, worked for me. basically you insert a unique text in the rich text area, then you get the index of the inserted text then you remove it.

    richText=new RichTextArea();
    basicFormatter=richText.getFormatter();
    basicFormatter.insertHTML("dummydata");
    int cursor=richText.getText().indexOf("dummydata");
    basicFormatter.undo();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!