滚动到 div 的底部不起作用
Scrolling to the bottom of a div is not working
我试图在单击某个按钮(聊天上下文)时将 div
滚动到底部,但它无法正常工作
在此聊天中,我需要在开始时在顶部显示消息,当我获得更多内容时自动滚动到底部以显示最新消息,我已经尝试了 scrollIntoView
,如下面的代码所示:
const element = this.$el.querySelector(".chat-box");
element.scrollIntoView({behavior: "smooth", block: "end"})
}
我希望滚动到 div
的末尾,但实际上滚动到底部附近,缺少一些内容。
只有 scrollIntoView
实际移动了卷轴,我试过了 element.scrollTop = element.scrollHeigh
但没有任何反应
我假设您是在与 scrollInToView
调用相同的回调中推送新消息?
这是我认为你在做什么:
this.messages.push(newMessage);
const element = this.$el.querySelector(".chat-box");
element.scrollIntoView({behavior: "smooth", block: "end"})
引用自Vue.js docs:
In case you haven’t noticed yet, Vue performs DOM updates asynchronously. Whenever a data change is observed, it will open a queue and buffer all the data changes that happen in the same event loop. If the same watcher is triggered multiple times, it will be pushed into the queue only once. This buffered de-duplication is important in avoiding unnecessary calculations and DOM manipulations. Then, in the next event loop “tick”, Vue flushes the queue and performs the actual (already de-duped) work.
这意味着您需要在尝试滚动到最后一个项目之前等待下一次勾选,所以这样的事情应该有效:
this.messages.push(newMessage);
// wait until the new message is rendered
this.$nextTick(() => {
// then scroll
const element = this.$el.querySelector(".chat-box");
element.scrollIntoView({behavior: "smooth", block: "end"})
});
我试图在单击某个按钮(聊天上下文)时将 div
滚动到底部,但它无法正常工作
在此聊天中,我需要在开始时在顶部显示消息,当我获得更多内容时自动滚动到底部以显示最新消息,我已经尝试了 scrollIntoView
,如下面的代码所示:
const element = this.$el.querySelector(".chat-box");
element.scrollIntoView({behavior: "smooth", block: "end"})
}
我希望滚动到 div
的末尾,但实际上滚动到底部附近,缺少一些内容。
只有 scrollIntoView
实际移动了卷轴,我试过了 element.scrollTop = element.scrollHeigh
但没有任何反应
我假设您是在与 scrollInToView
调用相同的回调中推送新消息?
这是我认为你在做什么:
this.messages.push(newMessage);
const element = this.$el.querySelector(".chat-box");
element.scrollIntoView({behavior: "smooth", block: "end"})
引用自Vue.js docs:
In case you haven’t noticed yet, Vue performs DOM updates asynchronously. Whenever a data change is observed, it will open a queue and buffer all the data changes that happen in the same event loop. If the same watcher is triggered multiple times, it will be pushed into the queue only once. This buffered de-duplication is important in avoiding unnecessary calculations and DOM manipulations. Then, in the next event loop “tick”, Vue flushes the queue and performs the actual (already de-duped) work.
这意味着您需要在尝试滚动到最后一个项目之前等待下一次勾选,所以这样的事情应该有效:
this.messages.push(newMessage);
// wait until the new message is rendered
this.$nextTick(() => {
// then scroll
const element = this.$el.querySelector(".chat-box");
element.scrollIntoView({behavior: "smooth", block: "end"})
});