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

爷,独闯天下 提交于 2019-11-27 16:42:19

问题


I want to get cursor position or the location from RichTextArea. I do not know how to get current cursor position Without any mouse event. e.g. TextArea has method getCursorPos(), but RichTextArea does not have method like TextArea. Anyone have any idea? Please help me...

Thanks in advance...


回答1:


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




回答2:


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



回答3:


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;
}-*/;



回答4:


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


来源:https://stackoverflow.com/questions/12542522/how-to-get-cursor-position-or-location-from-richtextarea-in-gwt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!