我打电话com.google.gwt.user.client.ui.TextArea.setText(myText)来设置内容。之后我调用setCursorPosition(myText.length())将光标移至末尾。这效果很好。
当myText文本区域的行数可以同时显示时,它会显示滚动条。但它不会滚动到光标位置。更糟糕的是 - 它滚动到顶部。
如何将 GWT TextArea 滚动到光标位置?我确实需要光标位置,而不是文本区域的底部。JSNI 解决方法也可以。
设置光标位置后尝试添加此内容:
textAreaToScroll.getElement().setScrollTop(textAreaToScroll.getElement().getScrollHeight());
Run Code Online (Sandbox Code Playgroud)
这会将元素滚动到底部。
编辑:
要滚动到任何光标位置(据我所知)没有简单的方法可以做到这一点。我认为没有任何方法可以询问浏览器光标所在的行。我只是想到了一些可能有效的想法(尚未实际测试过)来粗略估计滚动时间。
int cursorPos = textAreaToScroll.getCursorPos();
long offsetRatio = cursorPos / textAreaToScroll.getText().length();
//gives 0.0 to 1.0
offsetRatio += someMagicNumber; // -0.1 maybe?
// Depending on the font you may need to adjust the magic number
// to adjust the ratio if it scrolls to far or to short.
offsetRatio = offsetRatio>0.0 ? offsetRatio : 0; //make sure
//we don't get negative ratios
//(negative values may crash some browsers while others ignore it)
textAreaToScroll.getElement().setScrollTop(
textAreaToScroll.getElement().getScrollHeight() * offsetRatio );
Run Code Online (Sandbox Code Playgroud)
这可以大致滚动所需的距离。请注意,这假设每行填充的量大致相同,因为它使用光标位置除以文本长度而不是行数(很难计算)。手动换行会扭曲此估计,并且比例字体也会使其不太准确。
您可能需要调整比率,使其滚动得稍微太短而不是太远,因为如果光标略低于文本区域的顶部,光标仍然可见。
正如我所说,我还没有实际测试过这一点,我可能颠倒了逻辑和其他微妙的错误。
小智 3
我有一个场景,文本区域已经有一些东西,当提交新命令时,它将向其中添加数据并滚动到新添加的数据的开头。这就是我所做的
// Hold the previous height to set the scroll.
final int prevHeight = document.get().getElementById(textareadid).getScrollHeight();
// Hold the prev position if output area already has some data.
final int prevPos = this.textArea.getValue() != null ?
this.textArea.getValue().length() : 0;
Run Code Online (Sandbox Code Playgroud)
处理并设置新数据后
int posCount = 0;
if (previousResponse != null && !previousResponse.isEmpty())
{
final String dataStr = "new data from process";
// add 15 lines for the cursor position
posCount = getRelativeCount(dataStr);
}
this.textArea.getElement().setScrollTop(prevHeight);
this.textArea.setCursorPos(prevPos + posCount);
private int getRelativeCount(final String str)
{
int charCount = 0;
if (str != null)
{
int NUM_ROWS = 15;
if (getUserAgent().contains("msie"))
{
NUM_ROWS = 16;
}
final String[] splitArr = str.split("\n"); // split on the new line
// char
for (int index = 0; index < splitArr.length && index < NUM_ROWS; index++)
{
charCount += splitArr[index].length();
}
}
return charCount;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8980 次 |
| 最近记录: |