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

还应该提到这种方法取决于与组件内部结构有关的实现细节。这意味着存在在将来的某些版本中更改结构的风险,而不会将该更改视为重大更改。