javascript - TextArea 不会滚动到最大底部
问题描述
我有一个带有长文本的文本区域,我希望在视图显示时滚动到最大底部:
TextArea textArea = new TextArea();
textArea.setValue(createLongText());
textArea.setHeight("500px");
textArea.setMaxHeight("500px");
textArea.setWidthFull();
textArea.setReadOnly(false);
textArea.getElement().executeJs("this.inputElement.scrollTop = 500");
//text.setReadOnly(true);
textArea.getStyle().set("overflow-y", "auto ! important");
add(currentComponent = textArea);
我根据在网上找到的东西尝试了以下所有方法:
text.getElement().executeJs("this.inputElement.scrollTop = 1000"); //or scrollHeight
text.getElement().executeJs("this.scrollTop = 1000"); //or scrollHeight
text.getStyle().set("overflow-y", "auto ! important");
textArea.getElement()
.executeJs("this.inputElement.selectionStart= 1000;this.inputElement.selectionEnd= 1001;");
但这些都不起作用。
这是我的完整观点:
@Route("")
@PWA(name = "Project Base for Vaadin Flow with Spring", shortName = "Project Base")
@Secured("ROLE_ADMIN")
public class DashboardView extends VerticalLayout {
private Component currentComponent;
@Autowired
public DashboardView() {
Button longButtonText = new Button("Long textarea");
longButtonText.addClickListener(e -> {
if (currentComponent != null)
remove(currentComponent);
TextArea textArea = new TextArea();
textArea.setValue(createLongText());
textArea.setHeight("500px");
textArea.setMaxHeight("500px");
textArea.setWidthFull();
textArea.setReadOnly(false);
textArea.getElement().executeJs("this.inputElement.scrollTop = 500");
// text.setReadOnly(true);
textArea.getStyle().set("overflow-y", "auto ! important");
add(currentComponent = textArea);
});
Button logoutButton = new Button("logout");
logoutButton.addClickListener(e -> {
UI.getCurrent().getSession().close();
SecurityContextHolder.getContext().setAuthentication(null);
SecurityContextHolder.clearContext();
UI.getCurrent().getPage().setLocation("/login");
});
add(new HorizontalLayout(longButtonText, logoutButton));
longButtonText.click();
}
private String createLongText() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 2000; i++) {
sb.append(UUID.randomUUID().toString());
sb.append(System.lineSeparator());
}
return sb.toString();
}
}
我的 vaadin.version:<vaadin.version>14.1.17</vaadin.version>
我应该怎么做才能实现它?
解决方案
实际滚动的元素位于 DOM 层次结构的中间,而不是顶级组件或inputElement
. 我没有发现任何直接访问此元素的方法,因此您需要使用this.inputElement.parentElement.parentElement
.
要滚动到最后,您需要执行textArea.getElement().executeJs("this.inputElement.parentElement.parentElement.scrollTop = this.inputElement.parentElement.parentElement.scrollHeight");
.
还应该提到的是,这种方法依赖于与组件内部结构相关的实现细节。这意味着存在结构在某些未来版本中发生更改而没有将该更改视为重大更改的风险。
推荐阅读
- android - Android WebRTC 连接成功率低
- javascript - 让 React 在长时间运行的任务之间渲染页面
- android - 如何使用改造将图像发送到服务器
- jquery - Ajax 加载更多 - 如果没有更多内容,则隐藏按钮
- oracle - 在 oracle 中捕获子字符串
- c# - 需要帮助以在 Unity 2D 中使用计数器文本作为条件触发对话
- javascript - 将一个对象的属性名称复制到另一个而不复制值
- mongodb - Mongo 连接字符串问题 - 主机为空
- android - 如何在 Android sip stack SipManager 中拨打我的手机号码?
- java - 如何区分呼叫是移动呼叫还是IP呼叫?