自动滚动到垂直滚动条底部?

huangapple go评论53阅读模式
英文:

Auto-Scoll to Bottom for Vertical Scroller?

问题

Sure, here is the translated content without the code parts:

有没有办法自动滚动到Vaadin的垂直滚动Scroll组件的末尾?我已经尝试了类似的方法,但没有效果:

为了给你背景,我正在制作类似聊天的视图。消息以垂直布局显示,包装在Scroller组件中。

有什么想法吗?

编辑:
我将构造函数更改为附加JavaScript监听器。

“blur”事件当然不是正确的事件,但至少我可以看到效果。有人知道我应该在那里使用哪个其他事件吗?我已经尝试了“change”,但没有效果。

英文:

is it somehow possible to auto-scroll to the end of Vaadin's vertically scrolling Scroll component? I already tried something like, but with no effect:

    getElement().executeJs("""
        window.scrollTo(0, document.querySelector("#scrolling_div").scrollHeight);
        """);

To give you context, I am working on a chat-like view. Messages get displayed in a verical layout, wrapped in a Scroller component.

public class ChatLog extends Scroller {
  private final List<Component> messages = new ArrayList<>();
  private final VerticalLayout chatLog;

  public ChatLog() {
    chatLog = new VerticalLayout();

    addClassName("chat-view-scroller");
    setScrollDirection(Scroller.ScrollDirection.VERTICAL);
    setId("scrolling_div");
    setContent(chatLog);
  }

  private void scroll() {
    getElement().executeJs("""
        window.scrollTo(0, document.querySelector("#scrolling_div").scrollHeight);
        """);
  }

  public void newMessage(final String msg){
    ...
    scroll();
  }

...

Any ideas?

Edit:
I changed the constructor to attach a javascript listener

  public ChatLog() {
    chatLog = new VerticalLayout();
    addClassName("chat-view-scroller");
    setScrollDirection(Scroller.ScrollDirection.VERTICAL);
    setId("scrolling_div");
    setContent(chatLog);

    getElement().executeJs("""
        var el = this;
        el.addEventListener("blur", function(e) {
            el.scrollTo(0, document.body.scrollHeight);
            console.log("Test123486")
        });
        """);
  }

The "blur" event is of course not the correct one but at least I could see an effect there. Does anyone know what other event I should use there? I already tried "change", but it had no effect.

答案1

得分: 0

我现在让它工作了。这是我的解决方案:

public class ChatLog extends Scroller {
...

  private void scroll() {
    getElement().executeJs("""
        var el = this;
        el.scrollTo(0, el.scrollHeight);
        """);
  }

...

}

如果有人有更优雅的方法,请告诉我。感谢stackoverflow成为我的"橡皮鸭" 自动滚动到垂直滚动条底部?

英文:

I got it working now. Here's my solution:

public class ChatLog extends Scroller {
...

  private void scroll() {
    getElement().executeJs("""
        var el = this;
        el.scrollTo(0, el.scrollHeight);
        """);
  }

...

}

If anyone has a more elegant way to do it, let me know. Thanks stackoverflow for being my rubber duck 自动滚动到垂直滚动条底部?

huangapple
  • 本文由 发表于 2023年6月9日 13:37:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76437484.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定