首页 > 解决方案 > 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>

我应该怎么做才能实现它?

标签: javascriptjavaspring-bootvaadin

解决方案


实际滚动的元素位于 DOM 层次结构的中间,而不是顶级组件或inputElement. 我没有发现任何直接访问此元素的方法,因此您需要使用this.inputElement.parentElement.parentElement.

要滚动到最后,您需要执行textArea.getElement().executeJs("this.inputElement.parentElement.parentElement.scrollTop = this.inputElement.parentElement.parentElement.scrollHeight");.

还应该提到的是,这种方法依赖于与组件内部结构相关的实现细节。这意味着存在结构在某些未来版本中发生更改而没有将该更改视为重大更改的风险。


推荐阅读