如何在GWT RichTextArea中设置游标位置 [英] How to setcursor position in GWT RichTextArea
问题描述
有没有办法在GWT RichTextArea中设置cusror位置。在TextArea中有方法setCusrorPosition(),但RichTextArea中没有。
也许有一个原生的JavaScript(从GWT调用)可以设置RichTextArea中的光标位置?
Is there a way to set the cusror position in GWT RichTextArea. There is method setCusrorPosition() to do so in TextArea, but not in RichTextArea. Perhaps there is a native JavaScript (called from GWT) that could set the cursor position in the RichTextArea?
推荐答案
你是对的RichTextArea没有提供setSelectionRange方法,但是我已经使用JSNI创建了一个。
You are right RichTextArea is not providing the setSelectionRange method, but i have created one using the JSNI.
下面是方法,
public native void setSelectionRange(Element elem, int pos, int length) /*-{
try {
var selection = null, range2 = null;
var iframeWindow = elem.contentWindow;
var iframeDocument = iframeWindow.document;
selection = iframeWindow.getSelection();
range2 = selection.getRangeAt(0);
//create new range
var range = iframeDocument.createRange();
range.setStart(selection.anchorNode, pos);
range.setEnd(selection.anchorNode, length);
//remove the old range and add the newly created range
if (selection.removeRange) { // Firefox, Opera, IE after version 9
selection.removeRange(range2);
} else {
if (selection.removeAllRanges) { // Safari, Google Chrome
selection.removeAllRanges();
}
}
selection.addRange(range);
} catch (e) {
$wnd.alert(e);
}
}-*/;
使用上述方法写下面的代码:
For using above method write below code:
final RichTextArea tr = new RichTextArea();
Button b = new Button("Test");
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
setSelectionRange(tr.getElement(), 15, 20);
tr.setFocus(true);
}
});
RootPanel.get().add(tr);
RootPanel.get().add(b);
注意:记住要记住你传递的pos和length的验证检查setSelectionRange()方法。
此代码已在IE9,FF,Chrome中测试。
Note: Do remember to put the validation checks of "pos" and "length" you are passing in setSelectionRange() method. This code had been tested in IE9, FF, Chrome.
这篇关于如何在GWT RichTextArea中设置游标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!