我正在尝试在内容添加到其中时使 div 滚动。我正在使用一个 Vuejs 列表,它会随着源数组(vuejs 的数据数组)更改而更新项目。
<message v-for="message in messages"></message>
这是我的自动滚动伪代码:
let scroll = false;
messagesContainer.addMessageChild(new messageElement(...)); // addMessageChild appends item to vuejs's data, it may be async when it actually adds the element to the DOM which may cause the problem
if (messagesContainer.scrollTop = maxScrollOfMessagesContainer)
scroll = true;
messagesContainer.scrollTop = maxScrollOfMessagesContainer;
但是,消息容器元素不会滚动。我担心 Vuejs 可能会异步更新(插入)源(数据)中的元素,这种方式可能会跳过 if (messagesContainer.scrollTop = maxScrollOfMessagesContainer) 检查(在检查后添加元素(消息))。
我可以采取什么措施来防止这种情况发生?
最佳答案
滚动最后一条消息的方法怎么样?
模板:
<message v-for="message in messages" v-class="last-message : $index === (items.length-1)">
</message >
方法:
// smooth scroll on .last-message
scrollToLastMessage: function () {
document.querySelector('.last-message').scrollIntoView({
behavior: 'smooth'
})
}
// scroll when messages change
watch: {
messages: function () {
this.scrollToLastMessage()
}
}
// scroll when page ready
ready() {
this.scrollToLastMessage()
}
关于javascript - 自动滚动div问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47648253/